简体   繁体   English

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

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

I know you can create an anonymous function, 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. 在我看来,如果你想让事情变得更清楚,最好通过在那里添加类型注释而不是函数的结果来记录对标识符x的期望。

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. 因为在大多数情况下,如果它从Function下降,只有它是否有一个应用,它没有任何区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM