Kotlin Type Casting

Type conversion is a process in which one data type variable is converted into another data type. In Kotlin, implicit conversion of smaller data type into larger data type is not supported (as it supports in java). For example Int cannot be assigned into Long or Double.

  In Kotlin, conversion is done by explicit in which smaller data type is converted into larger data type and vice-versa. This is done by using helper function.


Helper Function for conversion

he list of helper functions used for numeric conversion in Kotlin is given below:

  toByte() : convert to Byte

  toShort() : convert to Short.

  toInt() : convert to Int.

  toLong() : convert to Long.

  toFloat() : convert to Float.

  toDouble() : convert to Double.

  toChar() : convert to Char.

Type conversion example

//Type conversion example
fun main(args: Array<String>) {
    //string example

    var a = 40
    var b = 50

    //converting a to double
    var d = a.toDouble()
    //converting a to Long type
    var l = a.toLong()

    println("value of double d = ${d}")
    println("value of loong l = ${l}")

}
value of double d = 40.0
value of loong l = 40