Kotlin Type Conversion

In Kotlin, a numeric value of one type is not automatically converted to another type even when the other type is larger. This is different from how Java handles numeric conversions. For example;

In Java,

int number1 = 55;
long number2 = number1;    // Valid code 

Here, value of number1 of type int is automatically converted to type long, and assigned to variable number2.

In Kotlin,

val number1: Int = 55
val number2: Long = number1   // Error: type mismatch.

Though the size of Long is larger than Int, Kotlin doesn't automatically convert Int to Long

Instead, you need to use toLong() explicitly (to convert to type Long). Kotlin does it for type safety to avoid surprises.

val number1: Int = 55
val number2: Long = number1.toLong()

Here's a list of functions in Kotlin used for type conversion:

Note, there is no conversion for Boolean types.


Conversion from Larger to Smaller Type

The functions mentioned above can be used in both directions (conversion from larger to smaller type and conversion from smaller to larger type).

However, conversion from larger to smaller type may truncate the value. For example,

fun main(args : Array<String>) {
    val number1: Int = 545344
    val number2: Byte = number1.toByte()
    println("number1 = $number1")
    println("number2 = $number2")
}

When you run the program, the output will be:

number1 = 545344
number2 = 64

Also check out these articles related to type conversion:

  • String to Int, and Int to String Conversion
  • Long to Int, and Int to Long Conversion
  • Double to Int, and Int to Double Conversion
  • Long to Double, and Double to Long Conversion
  • Char to Int, and Int to Char
  • String to Long, and Long to String Conversion
  • String to Array, and Array to String Conversion
  • String to Boolean, and Boolean to String Conversion
  • String to Byte, and Byte to String Conversion
  • Int to Byte, and Byte to Int Conversion
Did you find this article helpful?