Puzzlers on Kt. Academy, week 3

Marcin Moskala
Kt. Academy
Published in
3 min readApr 13, 2018

--

Time for new battery of Kotlin puzzlers. In this week is a bit challenging. Have fun :)

Composition

operator fun (() -> Unit).plus(f: () -> Unit) = {
this()
f()
}
fun main(args: Array<String>) {
({ print("Hello, ") } + { print("World") })()
}

Author: Marcin Moskala

What will it display? Some possibilities:
a) “Hello, World”
b) Error: Expecting top-level declaration
c) Error: Expression f cannot be invoked as a function
d) Error: Unresolved reference (operator + not defined for this types)
e) Works, but prints nothing

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

What am I?

fun main(args: Array<String>) {
val whatAmI = {}()
println(whatAmI)
}

Author: Dmitry Kandalov

What will it display? Some possibilities:

a) “null”
b) “kotlin.Unit”
c) Doesn’t print anything
d) Doesn’t compile

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

Return return

fun f1(): Int {
return return 42
}
fun f2() {
throw throw Exception()
}

Author: Dmitry Kandalov

How does f1 and f2 work? Some possibilities:
a) returns 42; throws exception
b) returns 42; doesn’t compile
c) doesn’t compile; throws exception
d) doesn’t compile; doesn’t compile

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

Answers and explanations

For “Composition” correct answer is:

a) “Hello, World”

Why? Here is an explanation:

Function `plus` is well defined. It returns new function (created using lambda expression) that composes two functions provided as arguments. When we add two functions, we have another function we can invoke. When we invoke it, we have lambda expressions invoked one after another.

For “What am I?” correct answer is:

b) “kotlin.Unit”

Why? Here is an explanation:

This is correct lambda expression that returns `Unit` when called.

For “Return return” correct answer is:

a) returns 42; throws exception

Why? Here is an explanation:

return expression has return type and can be used as an expression, but it also ends f1 execution with result 42. Similarly throw declares Nothing as a return type and compiles well, but before it is used method f2 is finished with exception.

Do you have your own idea for a puzzler? Submit it on 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.

--

--

Kt. Academy creator, co-author of Android Development with Kotlin, author of open-source libraries, community activist. http://marcinmoskala.com/