Kotlin - Data Type Cast

Introduction

Kotlin does not support automatic widening of numbers, so conversion must be invoked explicitly.

Each number has a function that will convert the value to one of the other number types.

To convert from an integer to a long we can do the following.

Demo

fun main(args: Array<String>) {

        val int = 123 
        val long = int.toLong() 
        /*  ww  w .  j  a va  2s. com*/
        println(int)
        print(long)
}

To convert a float to a double, we use the toDouble function.

Demo

fun main(args: Array<String>) {
        val float = 12.34F 
        val double = float.toDouble() 
        //w ww.j a v  a2 s .c om
        println(float)
        println(double)
}

The full list of functions for conversions between types is

  • toByte(),
  • toShort(),
  • toInt(),
  • toLong(),
  • toFloat(),
  • toDouble(),
  • toChar().