In this tutorial you will learn about the Kotlin Type Conversion and its application with practical example.
Kotlin Type Conversion
In Kotlin, a value of one type will not automatically converted to another type even when the other type is larger. This is different from how Java handles numeric conversions.
Example 1:- In Java
1 2 |
int num1 = 25; long num2 = num1; //Valid |
Here, value of num1 of type int is automatically converted to type long, and assigned to num2
Example 2:- In Kotlin
1 2 |
val num1: Int = 25 val num2: Long = num1 // Error: type mismatch. |
In Kotlin, the size of Long is larger than Int, but it doesn’t automatically convert Int to Long. Instead, you have to explicitly convert it Long to avoid type safety.
Here is a list of functions available in Kotlin for type conversion –
toByte()
toShort()
toInt()
toLong()
toFloat()
toDouble()
toChar()
Note:- There is no conversion for Boolean types.
Example:-
1 2 3 4 5 6 7 |
fun main(args : Array<String>) { println("W3Adda : Kotlin Type Conversion Example") val number1: Int = 25 val number2: Long = number1.toLong() println("After Conversion : "+number2) } |
Output:-
1 2 |
W3Adda : Kotlin Type Conversion Example After Conversion : 25 |