1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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) } |
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.