Kotlin Type Conversion
Many languages silently "widen" numbers — in Java you can store an int in a long variable without a second thought. Kotlin deliberately never converts types implicitly. Every conversion is an explicit function call, so you always see where a value changes type.
Implicit conversion is an error
fun main() {
val small: Int = 5
val big: Long = small
println(big)
}File.kt:3:19: error: Initializer type mismatch: expected 'Long', actual 'Int'.
Conversion functions
Every number type has functions to convert to the others:
| Function | Result type |
|---|---|
toByte() |
Byte |
toShort() |
Short |
toInt() |
Int |
toLong() |
Long |
toFloat() |
Float |
toDouble() |
Double |
toString() |
String |
fun main() {
val small: Int = 5
val big: Long = small.toLong()
val precise: Double = small.toDouble()
println(big)
println(precise)
println(small.toString() + "!")
}5
5.0
5!
Decimals to whole numbers
Converting a Double to an Int cuts off the decimal part (towards zero) — it does not round. Use roundToInt() from kotlin.math when you want rounding:
import kotlin.math.roundToInt
fun main() {
val score = 7.8
println(score.toInt())
println(score.roundToInt())
println((-7.8).toInt())
}7
8
-7
Arithmetic mixes types for you
While assignments are strict, arithmetic operators are overloaded for mixed types. The result has the "larger" type:
fun main() {
val items = 3 // Int
val unitPrice = 2.5 // Double
val total = items * unitPrice
println(total)
val a = 7
val b = 2
println(a / b) // Int / Int -> Int
println(a.toDouble() / b) // Double / Int -> Double
}7.5
3
3.5
Tip: Integer division (
7 / 2 == 3) is a classic bug. Convert one side toDoublewhen you need the fractional part.
Strings to numbers
Text from users or files must be parsed. toInt() throws an exception if the text isn't a valid number; toIntOrNull() returns null instead, which is usually the safer choice.
fun main() {
val input = "42"
val n = input.toInt()
println(n + 1)
println("3.75".toDouble())
println("abc".toIntOrNull())
println("12".toIntOrNull() ?: 0)
}43
3.75
null
12
The ?: ("Elvis") operator gives a default when the left side is null — you'll meet it again in the Null Safety chapter.
Chars and numbers
A Char is not a number in Kotlin. Use .code to get its Unicode code, and digitToInt() to turn '7' into 7:
fun main() {
val c = 'A'
println(c.code)
println(66.toChar())
println('7'.digitToInt() * 2)
}65
B
14
Test yourself
What does val x: Long = 10.toInt() do?
- Stores 10L
- Compile error: Int is not Long
- Throws at runtime
- Stores 10.0
What does 9.99.toInt() return?
- 10
- 9
- 9.99
- An error
What does "hello".toIntOrNull() return?
- 0
- -1
- null
- It throws NumberFormatException