Type Conversion in Kotlin

In this tutorial, we will learn about Type Conversion in Kotlin. In simple words type conversion means converting variable of one data type into another data type. It is important to note in Kotlin doesn't support implicit conversion of smaller data type into larger data type.

Invalid Type Conversion Example:

var num1 = 10  
val num2: Long = num1 //Compile error, type mismatch  

Kotlin also supports explicit type conversion. It means a programmer can explicitly convert smaller data type into larger data type and vice-versa. There are helper functions available in Kotlin to do this.

List of helper functions:

  • toByte()
  • toShort()
  • toInt()
  • toLong()
  • toFloat()
  • toDouble()
  • toChar()

Explicit Type Conversion Example:

fun main(args : Array<String>) {  
    var num1 = 10  
    val num2: Long =num1.toLong()  


Spread the love:

Please share this page on social media with your friends..

Facebook share Twitter Linkedin share

Great News! Now you can read all the tutorials on our Android App..

Download Owlbuddy: Learn Programming Tutorials App Now.

Download Owlbuddy: Learn Programming Tutorials