Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
820 views
in Technique[技术] by (71.8m points)

scala - Type inference on method return type

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)
}

But the following doesn't.

object Main {
    def who = return 5
    def main(args: Array[String]) = println(who)
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...