sweetyBaby sweetyBaby - 4 days ago 6
Scala Question

What is the issue with my foreach in Scala code

Below is my scala code, but line 13, there is an error says "missing parameter type", not sure what my problem?

class OneAway {

def isOneAway(s1:String, s2:String):Boolean={
if(s1.equals(s2))
return true
else if( s1.length > s2.length + 1 || s1.length < s2.length - 1)
return false
else
{
var count:Int=0
s1.chars().forEach(a=>{
if(a!=s2.charAt(count)){
return s2.substring(count+1).equals(s1.substring(count)) || s1.substring(count+1).equals(s2.substring(count))
}
count=count+1
}
)
return true
}

}
}

Answer

foreach should be all lowercase, plus lose the curly braces inside of it.

Also, even though you didn't ask ... This is a horrible way to write scala code. In 99% of the cases you'll ever run into, you'll want to avoid using returns, mutable state, and (with some exceptions) indexed access to sequences. Your code will also throw illegal index exceptions in some cases.

A proper way to do what you want in scala would be something like this:

@tailrec
def isOneAway(s1: String, s2: String): Boolean = (s1.headOption, s2.headOption) match {
  case (None, None) => true
  case (a,b) if a == b => isOneAway(s1.tail, s2.tail)
  case _ if s1.length == s2.length + 1 => s1.tail == s2
  case _ if s2.length == s1.length + 1 => s2.tail == s1        
  case _ => false
}
Comments