Kotlin Type Conversion Tutorial With Example

In this tutorial, we will learn about kotlin type conversion techniques. We will learn about how to convert kotlin variable from one data type to another data type. For example, from variable of data type Int to variable of data type Float, from data type Int to Double etc.

In Kotlin programming language, a numeric value is not automatically converted to another type even when other type is larger. You must explicitly convert it with the help of function calls etc. For example,

var a: Int  = 10
var b: Long = a    // This is invalid

You can not cast an Int variable to Long. Size of Long is larger than size of Int. Even then you can not convert Int to Long.

You will have to use toLong() function to convert Int to Long. So, below example word fine.

var a: Int  = 10
var b: Long = a.toLong()

Similarly, you will have to use appropriate method to convert one data type to another.

We are listing some functions that are frequently used to convert from one data type to another in kotlin –
toByte()
toLong()
toShort()
toFloat()
toChar()
toDouble()
toInt()

These methods can be used to convert variable of larger data types into smaller data types and vice-versa. However, while converting from larger data types to smaller data type, some value may get truncated. So, Double check your code before applying such method in code. Otherwise you may get surprise by the result.

Did you know?
There is no conversion for Boolean Data Type.

Exercises on Kotlin Type Conversion

1. Will below program execute successfully ?

fun main(args: Array<String>) {
  var a: Int  = 100.1
  var b: Long = a.toLong()
}

2. Will below program execute successfully ?

fun main(args: Array<String>) {
  var a: Int  = 100
  var b: Long = a
}

3. Will below program execute successfully ?

fun main(args: Array<String>) {
  var a: Int  = 100
  var b: Short = a.toShort()
}

4. Will below program execute successfully ?

fun main(args: Array<String>) {
  var a: Boolean  = true
  var b: Short = a.toShort()
}

That’s end of tutorial on Kotlin Type Conversion.

Leave a Reply