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.
Similar Programs Chapter Last Updated
Kotlin Continue Kotlin 02-03-2018
Kotlin Break Statement Kotlin 27-01-2018
Kotlin For Loop Kotlin 30-11-2017
Kotlin Do While Loop Kotlin 19-11-2017
Kotlin While Loop Kotlin 19-11-2017
Kotlin When Statement Kotlin 18-11-2017
Kotlin Nested If Kotlin 18-11-2017
Kotlin If Else If Statement Kotlin 22-09-2018
Kotlin If Statement Kotlin 17-11-2017
Kotlin Print And Println Kotlin 22-09-2018
Kotlin Logical Operators Kotlin 17-11-2017
Kotlin Assignment Operators Kotlin 15-11-2017
Kotlin Arithmetic Operators Kotlin 15-11-2017
Kotlin Data Types Kotlin 12-11-2017
Kotlin Variables Example Kotlin 11-11-2017
Kotlin Comments Example Kotlin 11-11-2017
Kotlin Hello World Kotlin 11-11-2017

1