Vishnu Haridas
11/01/2019, 2:08 PMwhen
expression that returns different types:
fun main(){
val x = readLine()?.toInt() ?: 0
val y = when(x){
1 -> 42
2 -> "Hello"
else -> 3.14F
}
println(y::class.java)
}
During runtime (Kotlin 1.3.41 on JVM 1.8) this is the output:
When x
= 1, it prints class java.lang.Integer
When x
= 2, it prints class java.lang.String
Otherwise, it prints class java.lang.Float
When does the compiler determine the type of y
? Or, how does the compiler infers the type of y
during compile-time?
Question on StackOverflow: https://stackoverflow.com/q/58479824/816416Pablichjenkov
11/01/2019, 2:14 PMy class
to be the upper bound class that cover all the when branches return types.
Or in other words, the super class that is common to all branches result.
Now KClass<T>.java
is a runtime function call. So it is acting on the actual returned type instance.Animesh Sahu
11/01/2019, 3:39 PMMaxim Kizub
11/01/2019, 4:15 PMStephan Schroeder
11/01/2019, 4:53 PMwhen
doesn’t return different types, it returns a value of typ Any
. So you wouldn’t be able to call y.substring(..)
without casting y
even if x=2
.Vishnu Haridas
11/01/2019, 4:59 PMwhen
returns the nearest supertype of all branches. In this case, Any
.
If we consider classes class Foo
, class Bar: Foo
, class Baz: Foo
, and a when
returns Bar
and Baz
in different branches, then the inferred type will be Foo
.y
to String
before we call y.subString()