English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn about type conversion. How to convert a variable of one type to another type with examples.
In Kotlin, a numeric value of one type will not automatically convert to another type, even if the other type is larger. This is different from how Java handles number conversions. For example:
In Java,
int number1 = 55; long number2 = number1; // Valid code
Here, the int type number1The value will be automatically converted to long type and assigned to the variable number2.
In Kotlin,
val number1: Int = 55 val number2: Long = number1 // Error: type mismatch.
AlthoughLongis larger than Int, but Kotlin will not automatically convert Int to Long.
On the contrary, you need to explicitly use toLong() (to convert to Long type). Kotlin does this to ensure type safety and avoid accidents.
val number1: Int = 55 val number2: Long = number1.toLong()
Below is a list of functions used for type conversion in Kotlin:
toByte() - Parse the string as a signed byte number and then return the result.
toShort() - Convert Int value to Short.
toInt() - Parse the string as an Int number and return the result.
toLong() - Parse the string as a Long number and return the result.
toFloat() - Parse the string as a Float number and return the result.
toDouble() - Parse the string as a Double number and return the result.
toChar() - Convert Int value to Char.
Note that there is no conversion for the Boolean type.
The function mentioned above can be used in both directions (conversion from a larger type to a smaller type and conversion from a smaller type to a larger type).
However, conversion from a larger type to a smaller type may truncate the value. For example,
fun main(args: Array<String>) { val number1: Int = 545344 val number2: Byte = number1.toByte() println("number1 =1") println("number2 =2") }
The output when running the program is:
number1 = 545344 number2 = 64