简体   繁体   English

Kotlin 如何用表达式体推断 function 的返回类型

[英]How Kotlin inferencing return type of function with expression body

If function consists of only one expression, than its return type may be infered from that expression.如果 function 仅包含一个表达式,则可以从该表达式推断其返回类型。 And it sounds pretty simple:这听起来很简单:

fun max(a: Int, b: Int) = if (a > b) a else b

In this case the return type of function will be Int.在这种情况下,function 的返回类型将为 Int。

But what type will be in the next example?但是下一个示例中将是什么类型?

fun max(a: Int, b: Int) = if (a > b) a else true

The inference just gives the closest ancestor of the types of the possible values of the expression.推断只是给出表达式可能值类型的最接近的祖先。

Here your expression can yield a Boolean or an Int .在这里,您的表达式可以产生BooleanInt The closest ancestor in this case is Comparable<*> , so that's the return type of your function.在这种情况下,最近的祖先是Comparable<*> ,所以这是 function 的返回类型。

If the types were completely unrelated, the common ancestor would be Any , which is in Kotlin the common ancestor of all non-nullable types.如果类型完全不相关,则共同祖先将是Any ,它在 Kotlin 中是所有不可为空类型的共同祖先。 If one of the values can also be null, you may end up with a return type that is Any?如果其中一个值也可以是 null,那么您最终可能会得到一个返回类型是Any? , which is the ultimate parent of all types in Kotlin (similar to Java's Object ). ,它是 Kotlin 中所有类型的最终父级(类似于 Java 的Object )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM