是否可以在Scala中指定匿名函数的返回类型? [英] Is it possible to specify an anonymous function's return type, in Scala?
本文介绍了是否可以在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.
推荐答案
在我看来,如果您想使事情变得更清楚,最好在标识符x上添加类型注释,而不是在代码x上记录对标识符x的期望.函数的结果.
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.
val x: () => Long = () => System.currentTimeMillis
然后,编译器将确保右侧的功能满足该期望.
Then the compiler will ensure that the function on the right hand side meets that expectation.
这篇关于是否可以在Scala中指定匿名函数的返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文