sweetyBaby sweetyBaby - 1 year ago 73
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={
return true
else if( s1.length > s2.length + 1 || s1.length < s2.length - 1)
return false
var count:Int=0
return s2.substring(count+1).equals(s1.substring(count)) || s1.substring(count+1).equals(s2.substring(count))
return true


Answer Source

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:

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download