方法返回类型的类型推断 [英] Type inference on method return type

查看:57
本文介绍了方法返回类型的类型推断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当方法中使用显式return语句时,为什么Scala无法推断方法的返回类型?

Why does Scala fail to infer the return type of the method when there's an explicit return statement used in the method?

例如,为什么下面的代码会编译?

For instance, why does the following code compile?

object Main {
    def who = 5
    def main(args: Array[String]) = println(who)
}

但以下没有.

object Main {
    def who = return 5
    def main(args: Array[String]) = println(who)
}

推荐答案

方法的返回类型要么是定义它的块中最后一条语句的类型,要么是定义它的表达式的类型,在没有块.

The return type of a method is either the type of the last statement in the block that defines it, or the type of the expression that defines it, in the absence of a block.

当您在方法中使用 return 时,您会引入另一个语句,该方法可能会从中返回.这意味着 Scala 无法在找到该 return 时确定它的类型.相反,它必须一直进行到方法结束,然后组合所有退出点以推断它们的类型,然后返回到每个退出点并分配它们的类型.

When you use return inside a method, you introduce another statement from which the method may return. That means Scala can't determine the type of that return at the point it is found. Instead, it must proceed until the end of the method, then combine all exit points to infer their types, and then go back to each of these exit points and assign their types.

这样做会增加编译器的复杂性并减慢它的速度,唯一的好处是在使用 return 时不必指定返回类型.另一方面,在目前的系统中,推断返回类型是从 Scala 已经使用的有限类型推断中免费获得的.

To do so would increase the complexity of the compiler and slow it down, for the sole gain of not having to specify return type when using return. In the present system, on the other hand, inferring return type comes for free from the limited type inference Scala already uses.

所以,最终,在编译器复杂性和获得的收益之间的平衡中,后者被认为不值得前者.

So, in the end, in the balance between compiler complexity and the gains to be had, the latter was deemed to be not worth the former.

这篇关于方法返回类型的类型推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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