Codementor Events

Puzzlers on Kotlin Academy, week 3

Published Apr 20, 2018
Puzzlers on Kotlin Academy, week 3

Originally published on: blog.kotlin-academy.com

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 Kotlin Academy portal.

Do you want more puzzlers in the future? Track Kotlin Academy portal or subscribe to our mailing list.

To be up-to-date with great news on Kotlin Academy, subscribe to the newsletter and observe Twitter.

Discover and read more posts from Kotlin Academy
get started
post commentsBe the first to share your opinion
Show more replies