In this section, we will learn what the type casting is and how it works in Kotlin.
What is Type Conversion or Type Casting in Kotlin?
Type conversion or type casting is the idea of converting the data type of one value into another data type.
For example, converting the value of an integer value into float or vice versa are examples of type conversion.
How To Type Cast in Kotlin?
In Kotlin, unlike other programming languages like Java, for example, there’s no concept of implicit type conversion! This means if you accidentally assigned a value of type integer into a variable of type float, for example, you’ll get an error as a result!
Every value must be explicitly converted first if we want to pass it to another data type.
Now, in order to convert one value from one data type to another one, we can use the built-in functions provided for that data type!
For example, a value of type integer has functions like:
toLong(), toFloat(), toShort(), toDouble() etc. that allows us to invoke them and convert the target value into the specified data type!
For example, to convert an integer value into float, we sue the toFloat() function. Or if we want to convert the value into short, we use the toShort() function.
Note that almost any built-in data type (including String, Char, Float, Double, Short etc.) They all have the mentioned functions. So if you want to convert a value of the mentioned data types into another data type, simply call one of these functions and your value will be converted into that data type.
Example: type casting in Kotlin
fun main(){ var sValue = "100" var iValue: Int = sValue.toInt() var fValue: Float = sValue.toFloat() var dValue: Double = sValue.toDouble() var lValue: Long = sValue.toLong() println(iValue) println(fValue) println(dValue) println(lValue) }
Output:
100 100.0 100.0 100
Example: type conversion in Kotlin
Note that if you have a string value and want to convert it into an integer or float, the content of that string value must be fully supported by the target data type!
For example, a string value that starts with number but also has other characters in it, won’t be converted using the mentioned functions and if we try to do so, we will get an error instead!
Also, if the string value contains only a float number but we want to convert it into integer value, we must first convert that string value into float type and then convert the result into integer! So it would be two steps of conversion in order to reach to the integer data type.
fun main(){ var sValue = "100.23" var iValue: Int = sValue.toFloat().toInt() println(iValue) }
Output:
100