27

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

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

仅仅为了静态类型,是否也可以指定它的返回类型?我认为这会让事情变得更清楚。

4

3 回答 3

57
val x = () => { System.currentTimeMillis } : Long
于 2010-01-18T19:10:52.770 回答
29

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

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

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

于 2010-01-18T19:19:47.523 回答
11

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

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

或者

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

甚至

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

因为在大多数情况下,如果它来自 Function 没有区别,只有它是否具有应用。

于 2010-01-19T01:16:24.990 回答