⇒ All number types support conversions to other types:
toByte(): Byte
toShort(): Short
toInt(): Int
toLong(): Long
toFloat(): Float
toDouble(): Double
→ In many cases, there is no need for explicit conversions because the type is inferred from the context, and arithmetical operations are overloaded for appropriate conversions, for example:
val l = 1L + 3 // Long + Int => Long
Type Conversion
Type conversion is when you convert the value of one data type to another type
- In Kotlin, numeric type conversion is different from Java. For example, it is not possible to convert an
Inttype to aLongtype with the following code:
- To convert a numeric data type to another type, you must use one of the following functions:
toByte(),toShort(),toInt(),toLong(),toFloat(),toDouble()ortoChar():
val x = 50 // Int val y : Long = x.toLong() // Long println(y)