Time for the new battery of Kotlin puzzlers from Kt. Academy! Have fun ;)

Map default

val map = mapOf<Any, Any>()

.withDefault{ "default" }

println(map["1"])

Author: Anton Keks

What will it display? Some possibilities:

a) default

b) nothing

c) null

d) will not compile

Check out answer and explanation using this link or by reading this article till the end.

Null empty

fun main(args: Array<String>) {

val s: String? = null

if (s?.isEmpty()) println("is empty")

if (s.isNullOrEmpty()) println("is null or empty")

}

Author: Dmitry Kandalov

What will it display? Some possibilities:

a) is empty is null or empty

b) is null or empty

c) prints nothing

d) doesn’t compile

Check out answer and explanation using this link or by reading this article till the end.

List or not

// Kotlin/JVM

fun main(args: Array<String>) {

val x = listOf(1, 2, 3)

print(x is List<*>)

print(x is MutableList<*>)

print(x is java.util.List<*>)

}

Author: Dmitry Kandalov

What will it display? Some possibilities:

a) true false true

b) false false true

c) true true true

d) true false false

Check out answer and explanation using this link or by reading this article till the end.

Answers and explanations

For “Map default” the correct answer is:

c) null

Why? Here is an explanation:

Map.withDefault() is misleading and can only be used with delegation https://youtrack.jetbrains.com/issue/KT-11851

For “Null empty” the correct answer is:

d) doesn’t compile

Why? Here is an explanation:

Expression s?.isEmpty() returns null when s == null so its type is Boolean? . Therefore we cannot use it in if directly. Fix:

fun main(args: Array) {

val s: String? = null if (s?.isEmpty() == true)

println(“is empty”)

if (s.isNullOrEmpty()) println(“is null or empty”)

}

For “List or not” the correct answer is:

c) true true true

Why? Here is an explanation: