Kotlin Type Conversion

Type conversion is a process in which one data type variable is converted into another data type. In Kotlin, implicit conversion of smaller data type into larger data type is not supported (as it supports in java). For example Int cannot be assigned into Long or Double.

In Java

int value1 = 10;  

long value2 = value1;  //Valid code   

    In Kotlin

      var value1 = 10  
    val value2: Long = value1  //Compile error, type mismatch 

      However in Kotlin, conversion is done by explicit in which smaller data type is converted into larger data type and vice-versa. This is done by using helper function.

      var value1 = 10  
      
      val value2: Long = value1.toLong()  

        The list of helper functions used for numeric conversion in Kotlin is given below:

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

        Kotlin Type Conversion Example

        Let see an example to convert from Int to Long.

        fun main(args : Array<String>) {  
        
            var value1 = 100  
        
            val value2: Long =value1.toLong()  
        
            println(value2)  
        
        } 

          We can also converse from larger data type to smaller data type.

          fun main(args : Array<String>) {  
          
              var value1: Long = 200  
          
              val value2: Int =value1.toInt()  
          
              println(value2)  
          
          }

          Comments

          Leave a Reply

          Your email address will not be published. Required fields are marked *