Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin Type Conversion

In Kotlin, unlike some other languages, there are no implicit widening conversions for numbers. This means you can't just assign a smaller type to a larger type variable. For instance, you can't assign an Int directly to a Long without an explicit conversion.

In this tutorial, we'll explore the methods Kotlin provides to convert between different data types.

1. Numeric Conversions:

Kotlin provides extension functions to convert between numeric types. Here are some of them:

  • Int: toInt(), toLong(), toFloat(), toDouble(), toByte(), toShort(), etc.

  • Long: toInt(), toLong(), toFloat(), toDouble(), toByte(), toShort(), etc.

  • Double: toInt(), toLong(), toFloat(), toDouble(), toByte(), toShort(), etc.

... and so on for other numeric types.

Example:

val intNum = 42
val longNum = intNum.toLong()
val doubleNum = intNum.toDouble()

2. From String to Other Types:

Often, we need to convert a String into a numeric type. For this, we use:

  • String.toInt(): Converts string to integer.
  • String.toDouble(): Converts string to double.
  • ... and similar methods for other types.

Note: If the string doesn't represent a valid number, these methods will throw a NumberFormatException.

Example:

val str = "12345"
val num = str.toInt()

For a safer conversion, which doesn't throw an exception but returns null for an invalid conversion, you can use:

val safeNum: Int? = str.toIntOrNull()

3. Char to Int:

Characters (Char) can be converted to their ASCII values using the toInt() method:

val char = 'A'
val ascii = char.toInt()
println(ascii)  // Outputs: 65

4. Explicit Casting:

While Kotlin requires explicit type conversion for number types, it allows traditional type casting using the as keyword for non-numeric types. Be cautious when using this, as it may throw a ClassCastException if the types are incompatible.

val anyObj: Any = "Hello, Kotlin!"
val strObj = anyObj as String

For a safer casting that returns null instead of throwing an exception, you can use as?:

val anyObj: Any = 12345
val strObj: String? = anyObj as? String  // This will be null

Conclusion:

Type conversions in Kotlin are explicit, which helps in writing safer code by avoiding unintended type promotions. Always remember to handle potential exceptions or use the safer "OrNull" versions of conversion functions when there's a chance of invalid data.

  1. Casting types in Kotlin:

    • Use casting to treat an object as another type.
    val anyValue: Any = "Hello, Kotlin!"
    val stringValue: String = anyValue as String
    
  2. Explicit vs implicit type conversion in Kotlin:

    • Explicit conversion requires the programmer's intervention, while implicit conversion happens automatically.
    val explicit: Int = 42
    val implicit: Double = explicit.toDouble() // Explicit to Double
    
  3. Converting between numeric types in Kotlin:

    • Convert between numeric types using appropriate methods.
    val intNumber: Int = 42
    val doubleNumber: Double = intNumber.toDouble()
    
  4. Type conversion with toXXX functions in Kotlin:

    • Utilize toXXX functions for type conversion.
    val intString: String = 42.toString()
    
  5. Type conversion and smart casting in Kotlin:

    • Leverage smart casting for safer type conversions.
    val value: Any = "Smart Cast"
    if (value is String) {
        println(value.length) // Smart cast to String
    }
    
  6. Working with nullable types and type conversion in Kotlin:

    • Handle nullable types with safe conversions.
    val nullableInt: Int? = 42
    val converted: Double? = nullableInt?.toDouble()
    
  7. Converting between primitive types and objects in Kotlin:

    • Kotlin automatically converts between primitive types and their corresponding objects.
    val primitiveInt: Int = 42
    val integerObject: Integer = primitiveInt
    
  8. Type conversion with custom functions in Kotlin:

    • Create custom functions for specialized type conversions.
    fun String.toCustomType(): CustomType {
        // Custom conversion logic
    }
    
    val customResult: CustomType = "Conversion".toCustomType()
    
  9. Type conversion and extension functions in Kotlin:

    • Extend existing types with conversion functions.
    fun Int.toDollars(): String {
        return "$$this"
    }
    
    val moneyString: String = 42.toDollars()
    
  10. Handling exceptions in type conversion in Kotlin:

    • Handle potential exceptions during type conversion.
    try {
        val invalidString: String = "Invalid".toInt()
    } catch (e: NumberFormatException) {
        println("Conversion failed: $e")
    }
    
  11. Type conversion in collections and arrays in Kotlin:

    • Convert types within collections and arrays.
    val intList: List<Int> = listOf(1, 2, 3)
    val doubleList: List<Double> = intList.map { it.toDouble() }