是否可以在 Scala 中指定匿名函数的返回类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2088524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to specify an anonymous function's return type, in Scala?
提问by Geo
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.
只是为了静态类型,是否也可以指定其返回类型?我认为这会让事情变得更加清晰。
回答by Fabian Steeg
val x = () => { System.currentTimeMillis } : Long
回答by Geoff Reedy
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.
然后编译器将确保右侧的函数满足该期望。
回答by psp
Fabian gave the straightforward way, but some other ways if you like micromanaging sugar include:
Fabian 给出了直截了当的方法,但如果您喜欢对糖进行微观管理,其他一些方法包括:
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 派生没有区别,只有它是否具有应用程序。

