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()  
    println(num2)  
}  

 

Spread the love
Scroll to Top
×