Challenge - 5 Problems
Kotlin Mastery: Why Kotlin over Java
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Kotlin code using null safety?
Consider this Kotlin code snippet that uses null safety features. What will it print?
Kotlin
fun main() { val name: String? = null val length = name?.length ?: -1 println(length) }
Attempts:
2 left
💡 Hint
Look at the Elvis operator ?: and how it handles null values.
✗ Incorrect
The variable name is nullable and set to null. The safe call operator ?. returns null for name?.length. The Elvis operator ?: then provides -1 as a default value. So, length becomes -1.
🧠 Conceptual
intermediate2:00remaining
Why does Kotlin reduce boilerplate compared to Java?
Which Kotlin feature helps reduce the amount of boilerplate code compared to Java?
Attempts:
2 left
💡 Hint
Think about how Kotlin handles simple classes with properties.
✗ Incorrect
Kotlin's data classes automatically generate equals(), hashCode(), toString(), and copy methods, reducing the need to write repetitive code.
🔧 Debug
advanced2:00remaining
Identify the error in this Kotlin code using coroutines
What error will this Kotlin coroutine code produce when run?
Kotlin
import kotlinx.coroutines.* fun main() { GlobalScope.launch { delay(1000L) println("World!") } println("Hello,") }
Attempts:
2 left
💡 Hint
Consider what happens to the main thread after launching a coroutine.
✗ Incorrect
The main function launches a coroutine but does not wait for it. The program exits immediately, so "World!" is never printed.
📝 Syntax
advanced2:00remaining
Which Kotlin syntax correctly declares a read-only list?
Choose the correct Kotlin syntax to declare a read-only list of integers containing 1, 2, and 3.
Attempts:
2 left
💡 Hint
Read-only lists use a specific Kotlin function.
✗ Incorrect
listOf() creates an immutable (read-only) list. mutableListOf() and arrayListOf() create mutable lists. List(1, 2, 3) is invalid syntax.
🚀 Application
expert3:00remaining
What is the output of this Kotlin code using sealed classes?
Given the sealed class hierarchy below, what will be printed when calling
describeShape with a Circle(5.0)?Kotlin
sealed class Shape class Circle(val radius: Double) : Shape() class Rectangle(val width: Double, val height: Double) : Shape() fun describeShape(shape: Shape): String = when(shape) { is Circle -> "Circle with radius ${shape.radius}" is Rectangle -> "Rectangle with width ${shape.width} and height ${shape.height}" } fun main() { println(describeShape(Circle(5.0))) }
Attempts:
2 left
💡 Hint
Sealed classes allow exhaustive when expressions without else.
✗ Incorrect
The when expression covers all subclasses of Shape. Passing a Circle(5.0) matches the first case and prints the radius.