Exercise: Using when
What will be the result of the following expressions?
private val magicNumbers = listOf(7, 13)
fun name(a: Any?): String = when (a) {
null -> "Nothing"
1, 2, 3 -> "Small number"
in magicNumbers -> "Magic number"
in 4..100 -> "Big number"
is String -> "String: $a"
is Int, is Long -> "Int or Long: $a"
else -> "No idea, really"
}
fun main() {
println(name(1)) // ?
println(name("A")) // ?
println(name(null)) // ?
println(name(5)) // ?
println(name(100)) // ?
println(name('A')) // ?
println(name("1")) // ?
println(name(-1)) // ?
println(name(101)) // ?
println(name(1L)) // ?
println(name(7)) // ?
println(name(3)) // ?
println(name(3.0)) // ?
println(name(100L)) // ?
}
Once you are done with the exercise, you can check your solution here.
Marcin Moskala is a highly experienced developer and Kotlin instructor as the founder of Kt. Academy, an official JetBrains partner specializing in Kotlin training, Google Developers Expert, known for his significant contributions to the Kotlin community. Moskala is the author of several widely recognized books, including "Effective Kotlin," "Kotlin Coroutines," "Functional Kotlin," "Advanced Kotlin," "Kotlin Essentials," and "Android Development with Kotlin."
Beyond his literary achievements, Moskala is the author of the largest Medium publication dedicated to Kotlin. As a respected speaker, he has been invited to share his insights at numerous programming conferences, including events such as Droidcon and the prestigious Kotlin Conf, the premier conference dedicated to the Kotlin programming language.