Type Safety in Kotlin: Understanding Numeric Conversions
When it comes to numeric values, Kotlin takes a distinct approach compared to Java. In Kotlin, a value of one type is not automatically converted to another type, even if the target type is larger. This design choice prioritizes type safety, avoiding unexpected surprises in your code.
A Key Difference from Java
In Java, the value of number1
of type int
is automatically converted to type long
and assigned to number2
. Not so in Kotlin. Despite Long
being larger than Int
, Kotlin refuses to make the conversion implicitly. Instead, you must use the toLong()
function explicitly to convert to type Long
.
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, when running a program, the output may not be what you expect.
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