Open In App

Kotlin Type Conversion

Last Updated : 01 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Type conversion (also called as Type casting) refers to changing the entity of one data type variable into another data type. As we know Java supports implicit type conversion from smaller to larger data types. An integer value can be assigned to the long data type. 

Example: 

Java




public class TypecastingExample { 
   public static void main(String args[]) { 
      byte p = 12
      System.out.println("byte value : "+p); 
                                                  // Implicit Typecasting 
      long q = p;                                  // integer value can be assigned
                                                 // to long data type   
   }
 }


But, Kotlin does not support implicit type conversion. An integer value can not be assigned to the long data type.  

var myNumber = 100
var myLongNumber: Long = myNumber       // Compiler error
// Type mismatch: inferred type is Int but Long was expected

In Kotlin, the helper function can be used to explicitly convert one data type to another data type. 

Example: 

var myNumber = 100
var myLongNumber: Long = myNumber.toLong()     // compiles successfully

The following helper function can be used to convert one data type into another:  

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

Note: There is No helper function available to convert into boolean type.

Conversion from larger to smaller data type

var myLongNumber = 10L
var myNumber2: Int = myLongNumber1.toInt()

Kotlin Program to convert the one data type into another:  

Kotlin




fun main(args: Array<String>)
{
   
    println("259 to byte: " + (259.toByte()))
    println("50000 to short: " + (50000.toShort()))
    println("21474847499 to Int: " + (21474847499.toInt()))
    println("10L to Int: " + (10L.toInt()))
    println("22.54 to Int: " + (22.54.toInt()))
    println("22 to float: " + (22.toFloat()))
    println("65 to char: " + (65.toChar()))
    // Char to Number is deprecated in kotlin
    println("A to Int: " + ('A'.toInt()))
}


Output: 

259 to byte: 3
50000 to short: -15536
21474847499 to Int: 11019
10L to Int: 10
22.54 to Int: 22
22 to float: 22.0
65 to char: A
A to Int: 65


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads