Geo*_*Geo 23 scala static-typing anonymous-function
我知道你可以创建一个匿名函数,让编译器推断它的返回类型:
val x = () => { System.currentTimeMillis }
仅为了静态类型,是否可以指定其返回类型?我认为这会让事情变得更加清晰.
Fab*_*eeg 50
val x = () => { System.currentTimeMillis } : Long
Geo*_*edy 29
在我看来,如果你想让事情变得更清楚,最好通过在那里添加类型注释而不是函数的结果来记录对标识符x的期望.
val x: () => Long = () => System.currentTimeMillis然后编译器将确保右侧的函数满足该期望.
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下降,只有它是否有一个应用,它没有任何区别.
| 归档时间: | 
 | 
| 查看次数: | 12375 次 | 
| 最近记录: |