Type Conversion
In this page:
No Implicit Widening
Unlike some languages, Kotlin never automatically converts an Int to a Double even though a Double can represent every Int value. Assigning across numeric types always requires an explicit conversion function.
Example: No Implicit Widening
fun main() {
val wholeNumber: Int = 10
val decimalNumber: Double = wholeNumber.toDouble()
println("Int: $wholeNumber, Double: $decimalNumber")
}
Login to try C/C++/Java/PHP code in the editor
Converting Between Numeric Types
Functions like toInt(), toLong(), toFloat(), and toDouble() convert a number from one numeric type to another, truncating or widening as appropriate.
Note: Converting a Double to an Int truncates the decimal part rather than rounding.
Example: Converting Between Numeric Types
fun main() {
val price: Double = 19.99
val roundedDown: Int = price.toInt()
println("Price: $price, as Int: $roundedDown")
}
Login to try C/C++/Java/PHP code in the editor
Converting Strings to Numbers
toInt(), toDouble(), and similar functions parse a String into a number, but they throw a NumberFormatException if the text is not a valid number.
Example: Converting Strings to Numbers
fun main() {
val text = "42"
val number = text.toInt()
println("Parsed number: ${number + 8}")
}
Login to try C/C++/Java/PHP code in the editor
Safe Conversion with OrNull
toIntOrNull(), toDoubleOrNull(), and similar functions return null instead of throwing when the string cannot be parsed, which is safer for handling untrusted input.
Example: Safe Conversion with OrNull
fun main() {
val goodInput = "123"
val badInput = "abc"
println("Good: ${goodInput.toIntOrNull()}")
println("Bad: ${badInput.toIntOrNull()}")
}
Login to try C/C++/Java/PHP code in the editor
- Expecting implicit widening conversions like in Java/C, such as assigning an
Intdirectly to aDoublevariable; Kotlin requires an explicittoDouble()call. - Using
asfor numeric conversions instead of the propertoInt()/toDouble()functions, which is meant for type casting, not conversion. - Calling
toInt()on a non-numeric string and not handling theNumberFormatExceptionthat results.
- Kotlin never performs implicit numeric conversions; every conversion between types like
IntandDoublemust be explicit. - Conversion functions like
toInt(),toDouble(),toLong(), andtoString()convert between numeric types and strings. - Converting a non-numeric string with
toInt()throws aNumberFormatExceptionat runtime. toIntOrNull()and similarOrNullvariants returnnullinstead of throwing when conversion fails.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: