In Kotlin, you can't just assign a smaller number type to a bigger one and expect it to work automatically. No implicit widening. You have to be explicit.
Why no automatic conversion?
Because automatic conversions hide bugs. If Kotlin silently turned your Int into a Long, you might accidentally lose precision or miss a logic error. Being explicit keeps your intentions clear.
The conversion functions
Every number type has conversion methods with obvious names:
fun main() {
val myInt: Int = 42
val myDouble: Double = myInt.toDouble()
val myString: String = myInt.toString()
val myLong: Long = myInt.toLong()
val myFloat: Float = myInt.toFloat()
println("Int: $myInt")
println("Double: $myDouble")
println("String: $myString")
println("Long: $myLong")
println("Float: $myFloat")
}
Converting from String
Got a number as text? Use toInt() or toDouble() to parse it.
fun main() {
val text = "123"
val number = text.toInt()
println(number + 1)
}
This prints 124. Without the conversion, you'd get a type error.
Try it Yourself โ