Kotlin Tutoial
Basics
Control Flow
Array & String
Functions
Collections
OOPs Concept
Exception Handling
Null Safety
Regex & Ranges
Java Interoperability
Miscellaneous
Android
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.
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.
val intNum = 42 val longNum = intNum.toLong() val doubleNum = intNum.toDouble()
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.Note: If the string doesn't represent a valid number, these methods will throw a NumberFormatException
.
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()
Characters (Char
) can be converted to their ASCII values using the toInt()
method:
val char = 'A' val ascii = char.toInt() println(ascii) // Outputs: 65
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
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.
Casting types in Kotlin:
val anyValue: Any = "Hello, Kotlin!" val stringValue: String = anyValue as String
Explicit vs implicit type conversion in Kotlin:
val explicit: Int = 42 val implicit: Double = explicit.toDouble() // Explicit to Double
Converting between numeric types in Kotlin:
val intNumber: Int = 42 val doubleNumber: Double = intNumber.toDouble()
Type conversion with toXXX functions in Kotlin:
toXXX
functions for type conversion.val intString: String = 42.toString()
Type conversion and smart casting in Kotlin:
val value: Any = "Smart Cast" if (value is String) { println(value.length) // Smart cast to String }
Working with nullable types and type conversion in Kotlin:
val nullableInt: Int? = 42 val converted: Double? = nullableInt?.toDouble()
Converting between primitive types and objects in Kotlin:
val primitiveInt: Int = 42 val integerObject: Integer = primitiveInt
Type conversion with custom functions in Kotlin:
fun String.toCustomType(): CustomType { // Custom conversion logic } val customResult: CustomType = "Conversion".toCustomType()
Type conversion and extension functions in Kotlin:
fun Int.toDollars(): String { return "$$this" } val moneyString: String = 42.toDollars()
Handling exceptions in type conversion in Kotlin:
try { val invalidString: String = "Invalid".toInt() } catch (e: NumberFormatException) { println("Conversion failed: $e") }
Type conversion in collections and arrays in Kotlin:
val intList: List<Int> = listOf(1, 2, 3) val doubleList: List<Double> = intList.map { it.toDouble() }