Consider the following Kotlin code snippet:
val x: Int = 10 val y: Long = x.toLong() println(y + 5L)
What will be printed?
val x: Int = 10 val y: Long = x.toLong() println(y + 5L)
Remember that toLong() converts Int to Long explicitly.
The variable x is converted explicitly to Long using toLong(). Adding 5L (a Long) results in a Long value of 15. The println prints 15.
Look at this Kotlin code:
val a: Int = 100 val b: Long = a println(b)
What error will it produce?
val a: Int = 100 val b: Long = a println(b)
Kotlin requires explicit conversion between numeric types.
Kotlin does not allow implicit widening conversions. Assigning an Int to a Long variable without explicit conversion causes a type mismatch error.
Examine this Kotlin snippet:
val num: Double = 12.5 val intNum: Int = num println(intNum)
Why does it fail to compile?
val num: Double = 12.5 val intNum: Int = num println(intNum)
Think about how Kotlin handles conversions between floating point and integer types.
Kotlin does not allow implicit conversion from Double to Int. You must use toInt() explicitly to convert.
Consider this Kotlin code:
val x: Byte = 10 val y: Int = x + 5 println(y)
What will be printed?
val x: Byte = 10 val y: Int = x + 5 println(y)
Check how Kotlin handles arithmetic with smaller integer types.
In Kotlin, arithmetic operations on Byte promote the value to Int. So x + 5 is an Int and can be assigned to y. The output is 15.
You have a nullable Int? variable num. You want to convert it to a non-nullable Long safely, providing 0L if num is null.
Which option does this correctly?
Consider safe calls and the Elvis operator for null handling.
Option A uses the safe call ?. to convert num to Long only if it is not null, otherwise returns null. The Elvis operator ?: provides 0L if num is null. This safely converts nullable Int? to non-nullable Long.
Option A fails if num is null (throws exception). Option A tries to assign Int? or Long directly, which is invalid. Option A is an unsafe cast and will fail at runtime if num is not a Long.