开发者

Odd behaviour with scala method syntax

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 r开发者_如何学编程eturn type here?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜