Kotlin Conversions
A conversion changes a value from one type into another type. Kotlin writes a conversion as a short call placed after the value.
A Double becomes an Int
The call toInt() drops the part after the point. The second print shows the stored value itself is unchanged.
fun main() {
val price = 3.9
println(price.toInt())
println(price)
}An Int becomes a Double
The call toDouble() adds a decimal point to the value. The new print shows 7.0 instead of 7.
fun main() {
val whole = 7
println(whole)
println(whole.toDouble())
}A String becomes a number
The call toInt() reads the digits in the text as a number. The changed value can then join arithmetic.
fun main() {
val text = "42"
println(text.toInt() + 1)
println(text.toInt() * 2)
}A number becomes text
The call toString() turns a number into a String. The String note on the variable makes the compiler check the new type. Changing the text back with toInt() and adding 1 gives 1235.
fun main() {
val count = 1234
val text: String = count.toString()
println(text)
println(text.toInt() + 1)
}A Double cannot sit in an Int variable
Placing a Double value into a variable marked Int does not compile. The program fails with this error.
fun main() {
val price = 9.99
val whole: Int = price
println(whole)
}Example
fun main() {
val scoreText = "85"
val score = scoreText.toInt()
println(score + 5)
println(score.toDouble() / 2)
val label: String = score.toString()
println(label)
}Key points
- Use toInt() to change a value into an Int.
- Use toDouble() to change a value into a Double.
- Use toString() to change a value into a String.
- toInt() on a Double drops the part after the point.
- toInt() on a String reads the digits in the text as a number.
In this example, scoreText holds the text 85 and toInt() changes it into the number 85. Adding 5 gives 90. Changing the score to a Double and dividing by 2 gives 42.5. The last print changes 85 back into text; the String note on label makes the compiler check that the value really is text.
Note
Kotlin does not change a value into another type on its own, so the call must be written out.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
A program sets val x = 6.8 and prints x.toInt(). What prints?