简体   繁体   中英

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. 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.

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 . The closest ancestor in this case is Comparable<*> , so that's the return type of your 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. If one of the values can also be null, you may end up with a return type that is Any? , which is the ultimate parent of all types in Kotlin (similar to Java's Object ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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