Kotlin Type Conversion
In Kotlin, type conversion can be done using type casting or conversion functions.
- Type casting: Type casting is used to convert a variable of one data type to another data type. It is denoted by the keyword
as
. Kotlin supports two types of type casting: safe and unsafe.
- Safe casting is used when you are not sure if a cast operation will succeed or not. It is denoted by the keyword
as?
. If the cast operation fails, it returnsnull
. Here's an example:
val x: Any = "Hello" val y: String? = x as? String println(y) // Output: "Hello"
- Unsafe casting is used when you are sure that a cast operation will succeed. It is denoted by the keyword
as
. If the cast operation fails, it throws aClassCastException
. Here's an example:
val x: Any = "Hello" val y: String = x as String println(y) // Output: "Hello"
- Conversion functions: Kotlin provides several built-in conversion functions that can be used to convert a value of one data type to another data type. Some of these functions include:
toByte()
,toShort()
,toInt()
,toLong()
,toFloat()
,toDouble()
: These functions are used to convert a numeric value to another numeric data type.toString()
: This function is used to convert any value to a string representation.
Here's an example that demonstrates the use of both type casting and conversion functions:
fun main() { val x: Any = 10 val y: String = "20" val a: Int = x as Int val b: Int = y.toInt() println("a = $a") println("b = $b") }
In this program, we use the as
keyword to cast the value of x
to an Int
, and we use the toInt()
function to convert the string value of y
to an Int
. We then print the values of a
and b
to the console. Note that if we try to cast y
to an Int
using the as
keyword, it will throw a ClassCastException
because the value of y
is not an Int
.