开发者

Is it possible to specify an anonymous function's return type, in Scala?

开发者 https://www.devze.com 2022-12-17 06:12 出处:网络
I know you can create an anonymous funct开发者_开发知识库ion, and have the compiler infer its return type:

I know you can create an anonymous funct开发者_开发知识库ion, and have the compiler infer its return type:

val x = () => { System.currentTimeMillis }

Just for static typing's sake, is it possible to specify its return type as well? I think it would make things a lot clearer.


val x = () => { System.currentTimeMillis } : Long


In my opinion if you're trying to make things more clear it is better to document the expectation on the identifier x by adding a type annotation there rather than the result of the function.

val x: () => Long = () => System.currentTimeMillis

Then the compiler will ensure that the function on the right hand side meets that expectation.


Fabian gave the straightforward way, but some other ways if you like micromanaging sugar include:

val x = new (() => Long) {
  def apply() = System.currentTimeMillis
}

or

val x = new Function0[Long] {
  def apply() = System.currentTimeMillis
}

or even

val x = new {
  def apply(): Long = System.currentTimeMillis
}

since in most situations it makes no difference if it descends from Function, only whether it has an apply.

0

精彩评论

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