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 endsf1
execution with result42
. Similarlythrow
declaresNothing
as a return type and compiles well, but before it is used methodf2
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.