是否可以在 Scala 中指定匿名函数的返回类型? [英] Is it possible to specify an anonymous function's return type, in Scala?

查看:28
本文介绍了是否可以在 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 上添加类型注释而不是函数的结果.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆