0
0
Kotlinprogramming~20 mins

Type conversion is always explicit in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Kotlin Type Conversion Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Kotlin code with explicit type conversion?

Consider the following Kotlin code snippet:

val x: Int = 10
val y: Long = x.toLong()
println(y + 5L)

What will be printed?

Kotlin
val x: Int = 10
val y: Long = x.toLong()
println(y + 5L)
A15
B15L
C15.0
DCompilation error
Attempts:
2 left
💡 Hint

Remember that toLong() converts Int to Long explicitly.

Predict Output
intermediate
2:00remaining
What error does this Kotlin code produce?

Look at this Kotlin code:

val a: Int = 100
val b: Long = a
println(b)

What error will it produce?

Kotlin
val a: Int = 100
val b: Long = a
println(b)
AType mismatch: inferred type is Int but Long was expected
BNo error, prints 100
CNullPointerException
DUnresolved reference: Long
Attempts:
2 left
💡 Hint

Kotlin requires explicit conversion between numeric types.

🔧 Debug
advanced
2:00remaining
Why does this Kotlin code fail to compile?

Examine this Kotlin snippet:

val num: Double = 12.5
val intNum: Int = num
println(intNum)

Why does it fail to compile?

Kotlin
val num: Double = 12.5
val intNum: Int = num
println(intNum)
ABecause Double cannot be assigned to Int due to null safety
BBecause println cannot print Int variables
CBecause Kotlin requires explicit conversion from Double to Int using toInt()
DBecause val variables cannot be reassigned
Attempts:
2 left
💡 Hint

Think about how Kotlin handles conversions between floating point and integer types.

Predict Output
advanced
2:00remaining
What is the output of this Kotlin code with explicit conversion and arithmetic?

Consider this Kotlin code:

val x: Byte = 10
val y: Int = x + 5
println(y)

What will be printed?

Kotlin
val x: Byte = 10
val y: Int = x + 5
println(y)
AByte overflow error
BCompilation error due to type mismatch
C10
D15
Attempts:
2 left
💡 Hint

Check how Kotlin handles arithmetic with smaller integer types.

🧠 Conceptual
expert
2:00remaining
Which Kotlin statement correctly converts a nullable Int to a non-nullable Long safely?

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?

Aval result: Long = num?.toLong() ?: 0L
Bval result: Long = num.toLong()
Cval result: Long = num ?: 0L
Dval result: Long = num as Long
Attempts:
2 left
💡 Hint

Consider safe calls and the Elvis operator for null handling.