Type Safety in Kotlin: Understanding Numeric Conversions
A Key Difference from Java
In Java, a value of one type is automatically converted to another type, even if the target type is larger. However, Kotlin takes a distinct approach, prioritizing type safety by refusing to make implicit conversions.
int number1 = 10;
long number2 = number1; // implicit conversion in Java
In Kotlin, this would not be allowed:
val number1: Int = 10
val number2: Long = number1 // error: type mismatch
Instead, you must use the toLong()
function explicitly to convert to type Long
:
val number1: Int = 10
val number2: Long = number1.toLong()
The Power of Explicit Conversions
Kotlin’s explicit conversion approach ensures that you’re always in control of your code’s behavior. By requiring explicit conversions, Kotlin eliminates the risk of unexpected type mismatches. This design choice also encourages developers to think carefully about the types they’re working with.
Your Go-To Conversion Functions
Kotlin provides a range of functions for type conversion:
toByte()
toShort()
toInt()
toLong()
toFloat()
toDouble()
toChar()
Note that there’s no conversion function for Boolean types.
Converting Between Types: Larger to Smaller
While the above functions can be used for both larger-to-smaller and smaller-to-larger conversions, beware that converting from a larger type to a smaller one may truncate the value. For example:
val largeValue: Long = 1000000000
val smallValue: Int = largeValue.toInt() // may truncate the value
Related Reading
Want to dive deeper into type conversion? Check out these related articles:
- String to Int, and Int to String Conversion
- Long to Int, and Int to Long Conversion
- Double to Int, and Int to Double Conversion
- Long to Double, and Double to Long Conversion
- Char to Int, and Int to Char
- String to Long, and Long to String Conversion
- String to Array, and Array to String Conversion
- String to Boolean, and Boolean to String Conversion
- String to Byte, and Byte to String Conversion
- Int to Byte, and Byte to Int Conversion