No Automatic Number Conversions
In many programming languages, you can convert numbers between shorter representations (like a Java int
) and longer representations (like a Java long
) just via assignments. The compiler knows to “upsize” the value.
In Kotlin, though, that only works for literals, not variables.
So, for example, as we saw earlier, this works:
var count: Long = 5
println(count::class)
However, this does not compile:
val thisIsInt = 5
val thisIsLong : Long = thisIsInt
println(thisIsLong::class)
The compiler error will be something akin to:
error: type mismatch: inferred type is Int but Long was expected
val thisIsLong : Long = thisIsInt
Kotlin wants you to intentionally perform such conversions. There is a toLong()
function that does the trick:
val thisIsInt = 5
val thisIsLong : Long = thisIsInt.toLong()
println(thisIsLong::class)
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.