Kotlin Type Conversion
Chapter:
Kotlin
Last Updated:
17-11-2017 07:16:09 UTC
Program:
/* ............... START ............... */
fun main(args : Array<String>) {
/* In java we can assign value like this but in kotlin it will give error
int number1 = 45;
long number2 = number1;
*/
/* If we write code in kotlin it will look like this. It willt throw type mismatch error
val number1: Int = 45
val number2: Long = number1 // Error: type mismatch.
*/
//toLong explicitly converts to long
println("Kotlin Type Conversion Example")
val number1: Int = 45
val number2: Long = number1.toLong()
println("After Conversion : "+number2)
}
/* ............... END ............... */
Output
Kotlin Type Conversion Example
After Conversion : 45
Notes:
-
In Kotlin, a numeric 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.
- In the above program you can see that size of Long is larger than Int, but Kotlin doesn't automatically convert Int to Long.
- In Kotlin we need to use toLong() explicitly to convert to Long. Please go through the program which explains about the Type Conversion in Kotlin.
Tags
Type Conversion , Kotlin