2

I hit a bit of a quirk of scala's syntax I don't really understand

object Board {
   def getObjectAt(x:Int, y:Int):Placeable = return locations(x)(y)
}

works fine. But

object Board {
   def getObjectAt(x:Int, y:Int):Placeable {
      return locations(x)(y)
   }
}

returns the error

Board.scala:8: error: illegal start of declaration
return locations(x)(y)

I found some stuff that says the second form convinces the scala compiler you're trying to specify an expansion to the return type Placeable. Is there a way I can fix this, or should I just avoid specifying a return type here?

2
  • 4
    BTW the "return" keyword is superfluous and can be omitted. In the absence of an explicit return statement Scala returns the last value computed by the method. Recommended style is to avoid explicit methods (especially multiple returns). Commented Jun 14, 2010 at 6:34
  • possible duplicate of When to use the equals sign in a Scala method declaration? Commented Apr 9, 2012 at 4:45

1 Answer 1

10

It's just about the function syntax.

If your function has a return value, you'll always define it as an equation (using =), even if a block of computations follows:

object Board {
   def getObjectAt(x:Int, y:Int):Placeable = {
      return locations(x)(y)
   }
}

The notation

def func(...) { ...

is shorthand for return-type Unit, i.e. a function without return value.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.