Kotlin Type Conversion With Examples

 
In this post, You can learn how to convert variable of one type to another. Type Conversion is a process of changing one data type variable into another data type.

A numeric type of variable is not automatically converted to another numeric type in kotlin language. Type Conversion is also known as Type Casting. Type Conversion means convert one variable of one type to another type.
 

Difference with Java

Implicit conversion of smaller data type into larger is supported in Java. But it is not supported in Kotlin. In Kotlin, We need to explicitly do Type Conversion.
 

For Example
In Java

int num1 = 11;
long num2 = num1; // Automatically converted
 

In Kotlin

val num1: Int = 11
val num2: Long = num1 // Compile Error
 
So We need to explicitly convert Int type to Long type
val num1: Int = 11
val num2: Long = num1.toLong()
 
 

Function used for Type Conversion in Kotlin

  1. toByte() : To convert any data type to Byte data type
  2. fun main (args: Array<String>) {
         println (“11 to byte: ” + 11.toByte() )
    }
     
  3. toShort() : To convert any data type to Short data type
  4. fun main (args: Array<String>) {
         println (“23 to short: ” + 23.toShort() )
    }
     
  5. toInt() : To convert any data type to Int data type
  6. fun main (args: Array<String>) {
         println (“14.34 to Int: ” + 14.34.toInt() )
    }
     
  7. toLong() : To convert any data type to Long data type
  8. fun main (args: Array<String>) {
         println (“142 to long: ” + 142.toLong() )
    }
     
  9. toFloat() : To convert any data type to Float data type
  10. fun main (args: Array<String>) {
         println (“21 to float: ” + 21.toFloat() )
    }
     
  11. toDouble() : To convert any data type to Double data type
  12. fun main (args: Array<String>) {
         println (“21 to double: ” + 21.toDouble() )
    }
     
  13. toChar() : To convert any data type to Char data type
  14. fun main (args: Array<String>) {
         println (“43 to char: ” + 43.toChar() )
    }

Leave a Reply