Converting one data type into another
In Java, we used to typecast by appending the desired type in front of variables like this:
String a = Integer.toString(10)
Also, in Java, numeric is directly converted to larger numeric types, but in Kotlin, this feature is not there for type safety—so how can we change one type of object to another in Kotlin? We will see it in this recipe.
Getting ready
You need to install a preferred development environment that compiles and runs Kotlin. You can also use the command line for this purpose, for which you need Kotlin compiler installed, along with JDK. I am using the online IDE available at https://try.kotlinlang.org/ to compile and run my Kotlin code for this recipe.
How to do it...
Let's understand how to convert one data type into another by following the steps below:
- Let's try a very basic example—trying to convert an
Int
toLong
andFloat
:
fun main(args: Array<String>) { var a = 1 var b: Float = a.toFloat() var c = a.toLong() println...