Puzzlers on Kt. Academy, week 14
Weekly set of Kotlin puzzlers is waiting for you — challenge yourself!
Lazy delegate
class Lazy {
var x = 0
val y by lazy { 1/x }
fun hello() {
try {
print(y)
} catch (e: Exception) {
x = 1
print(y)
}
}
}
fun main(args: Array<String>) {
Lazy().hello()
}
Author: Anton Keks
What will it display? Some possibilities:
a) 0
b) 1
c) NaN
d) ArithmeticException
Check out the answer and explanation using this link or by reading this article till the end.
Sneaky return
fun numbers(list: List<Int>) {
list.forEach {
if (it > 2) return
print(it)
}
print("ok")
}
fun main(args: Array<String>) {
numbers(listOf(1, 2, 3))
}
Author: Anton Keks
What will it display? Some possibilities:
a) 123ok
b) 12ok
c) 12
d) Infinite loop
Check out the answer and explanation using this link or by reading this article till the end.
Two lambdas
typealias L = (String) -> Unit
fun foo(one: L = {}, two: L = {}) {
one("one")
two("two")
}
fun main(args: Array<String>) {
foo { print(it) }
foo({ print(it) })
}
Author: Anton Keks
What will it display? Some possibilities:
a) oneone
b) twotwo
c) onetwo
d) none of the above
Check out the answer and explanation using this link or by reading this article till the end.
Answers and explanations
For “Lazy delegate” the correct answer is:
b) 1
Why? Here is an explanation:
Lazy delegate can be called multiple times until it actually returns a value Delegate exceptions are be propagated out of the getter
For “Sneaky return” the correct answer is:
c) 12
Why? Here is an explanation:
In Kotlin, return returns from the nearest function declaration Unlike Java, you cannot return from a lambda — lambda returns an expression Using return within lambda is only possible in inline functions This is confusing at first but becomes pretty straightforward later
See more in here: https://github.com/angryziber/kotlin-puzzlers/blob/master/src/functions/sneakyReturn/KeywordHell.kt
For “Two lambdas” the correct answer is:
d) none of the above (twoone)
Why? Here is an explanation:
Lambda in parentheses is applied as the first argument Lambda without parentheses is defined to be applied as the last argument
- This is great for DSLs
- But can be confusing when combined with default parameters Do not take many lambdas as arguments, and avoid default values if you still do it
Do you have your own idea for a puzzler? Submit it to Kt. Academy portal.
Do you want more puzzlers in the future? Track Kt. Academy portal or subscribe to our mailing list.
Do you need a Kotlin workshop? Visit our website to see what we can do for you.
If you like it, remember to clap. Note that if you hold the clap button, you can leave more claps.