in , ,

Kotlin Type Conversion

Kotlin Type Conversion
Kotlin Type Conversion

Kotlin Type Conversion: In this tutorial, you will learn about type conversion; how to convert a variable of one sort to another with the assistance of an example.

Type conversion is a process where one data type variable is converted into another data type. In Kotlin, implicit conversion of smaller data types into larger data types isn’t supported (as it supports in java). For instance, Int can’t be assigned into Long or Double.

In Kotlin, a numeric value of one sort isn’t consequently converted to another type in any event, when the other sort is larger. This is different from how Java handles numeric conversions. For instance;

In Java,

int number1 = 55;
long number2 = number1;    // Valid code 

Here, value of number1 of type int is automatically converted to type long, and assigned to variable number2.

In Kotlin,

val number1: Int = 55
val number2: Long = number1   // Error: type mismatch.

In spite of the fact that the size of Long is larger than Int, Kotlin doesn’t automatically convert Int to Long.

Instead you need to use toLong() expressly (to convert to type Long). Kotlin does it for type wellbeing to maintain a strategic distance from shocks.

val number1: Int = 55
val number2: Long = number1.toLong()

Here’s a list of functions in Kotlin used for type conversion:

Note, there is no conversion for Boolean types.


Conversion from Larger to Smaller Type

The functions referenced above can be used in two ways (conversion from larger to smaller sort and conversion from smaller to larger type).

Nonetheless, conversion from larger to smaller sort may shorten the worth. For instance,

fun main(args : Array<String>) {
    val number1: Int = 545344
    val number2: Byte = number1.toByte()
    println("number1 = $number1")
    println("number2 = $number2")
}

At the point when you run the program, the output will be:

number1 = 545344
number2 = 64

Also check out these articles related to type conversion:

  • String to Int, and Int to String Conversion
  • Long to Int, and Int to Long Conversion
  • Double to Int, and Int to Double Conversion
  • Long to Double, and Double to Long Conversion
  • Char to Int, and Int to Char
  • String to Long, and Long to String Conversion
  • String to Array, and Array to String Conversion
  • String to Boolean, and Boolean to String Conversion
  • String to Byte, and Byte to String Conversion
  • Int to Byte, and Byte to Int Conversion

Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.

Kotlin Introduction

salman khan

Written by worldofitech

Leave a Reply

Kotlin Operators

Kotlin Operators

Kotlin Expression, Statements, and Blocks

Kotlin Expression, Statements, and Blocks