是否可以在Scala中指定匿名函数的返回类型?

Geo*_*Geo 23 scala static-typing anonymous-function

我知道你可以创建一个匿名函数,让编译器推断它的返回类型:

val x = () => { System.currentTimeMillis }
Run Code Online (Sandbox Code Playgroud)

仅为了静态类型,是否可以指定其返回类型?我认为这会让事情变得更加清晰.

Fab*_*eeg 50

val x = () => { System.currentTimeMillis } : Long
Run Code Online (Sandbox Code Playgroud)


Geo*_*edy 29

在我看来,如果你想让事情变得更清楚,最好通过在那里添加类型注释而不是函数的结果来记录对标识符x的期望.

val x: () => Long = () => System.currentTimeMillis
Run Code Online (Sandbox Code Playgroud)

然后编译器将确保右侧的函数满足该期望.


psp*_*psp 9

Fabian给出了直截了当的方式,但是如果你喜欢微观管理糖,其他一些方法包括:

val x = new (() => Long) {
  def apply() = System.currentTimeMillis
}
Run Code Online (Sandbox Code Playgroud)

要么

val x = new Function0[Long] {
  def apply() = System.currentTimeMillis
}
Run Code Online (Sandbox Code Playgroud)

甚至

val x = new {
  def apply(): Long = System.currentTimeMillis
}
Run Code Online (Sandbox Code Playgroud)

因为在大多数情况下,如果它从Function下降,只有它是否有一个应用,它没有任何区别.