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: