0
0
Kotlinprogramming~5 mins

Type conversion is always explicit in Kotlin

Choose your learning style9 modes available
Introduction

In Kotlin, you must clearly tell the computer when you want to change a value from one type to another. This helps avoid mistakes.

When you want to change a number from one type to another, like from Int to Double.
When you need to convert a character to its numeric code or vice versa.
When you want to store a smaller type value into a bigger type variable explicitly.
When you want to avoid unexpected errors by making conversions clear in your code.
Syntax
Kotlin
val newValue = oldValue.toType()

You use functions like toInt(), toDouble(), toLong(), etc.

Implicit conversions (automatic) do not happen in Kotlin, so you must call these functions yourself.

Examples
Convert an Int to a Double explicitly using toDouble().
Kotlin
val a: Int = 10
val b: Double = a.toDouble()
Convert a Double to an Int explicitly using toInt(). This drops the decimal part.
Kotlin
val c: Double = 3.14
val d: Int = c.toInt()
Get the numeric code of a character using the code property.
Kotlin
val e: Char = 'A'
val f: Int = e.code
Sample Program

This program shows how to convert an Int to a Double and a Double to an Int explicitly in Kotlin.

Kotlin
fun main() {
    val intVal: Int = 42
    val doubleVal: Double = intVal.toDouble()
    println("Int value: $intVal")
    println("Converted to Double: $doubleVal")

    val doubleNum: Double = 9.99
    val intNum: Int = doubleNum.toInt()
    println("Double value: $doubleNum")
    println("Converted to Int: $intNum")
}
OutputSuccess
Important Notes

Always use explicit conversion functions to avoid confusion and errors.

Converting from Double to Int removes the decimal part; it does not round.

There is no automatic conversion between numeric types in Kotlin.

Summary

Kotlin requires you to convert types explicitly using functions like toInt() or toDouble().

This makes your code safer and clearer.

Remember that some conversions may lose information, like dropping decimals.