Puzzlers on Kotlin Academy, week 4
Originally published on blog.kotlin-academy.com
Today we will touch Kotlin documentation and we will try to use Kotlin like Java. Have fun
Extensions are resolved statically
open class C
class D: C()
fun C.foo() = "c"
fun D.foo() = "d"
fun printFoo(c: C) {
println(c.foo())
}
fun main(args: Array<String>) {
printFoo(D())
}
Author: Kotlin documentation
What will it display? Some possibilities:
a) Doesn’t compile
b) Runtime error
c) c
d) d
Check out answer and explanation using this link or by reading this article till the end.
Expression or not
fun f1() {
var i = 0
val j = i = 42
println(j)
}
fun f2() {
val f = fun() = 42
println(f)
}
fun f3() {
val c = class C
println(c)
}
Author: Dmitry Kandalov
What is the result of f1
, f2
and f3
? Some possibilities:
a) 42
() -> kotlin.Int
class C
b) 42
() -> kotlin.Int
doesn’t compile
c) doesn’t compile
() -> kotlin.Int
doesn’t compile
d) doesn’t compile
doesn’t compile
doesn’t compile
Check out answer and explanation using this link or by reading this article till the end.
Eager or lazy?
fun main(args: Array<String>) {
val x = listOf(1, 2, 3).filter { print("$it "); it >= 2 }
print("before sum ")
println(x.sum())
}
Author: Dmitry Kandalov
What will it display? Some possibilities:
a) 1 2 3 before sum 5
b) 2 3 before sum 5
c) before sum 1 2 3 5
d) order is not deterministic
Check out answer and explanation using this link or by reading this article till the end.
Answers and explanations
For “Extensions are resolved statically” the correct answer is:
c) “c”
Why? Here is an explanation:
This example will print “c” because the extension function being called depends only on the declared type of the parameter c, which is the C class.
Extensions do not actually modify classes they extend. By defining an extension, you do not insert new members into a class, but merely make new functions callable with the dot-notation on variables of this type.
For “Expression or not” the correct answer is:
c) doesn’t compile
() -> kotlin.Int
doesn’t compile
Why? Here is an explanation:
Variable initialization and class declaration are both statements in Kotlin and they don’t declare any return type. We cannot assign such declarations to variables. In
f2
we have an anonymous function.
For “Eager or lazy?” the correct answer is:
a) 1 2 3 before sum 5
Why? Here is an explanation:
Unlike Java8 streams, collection extension function in Kotlin are eager.
sequenceOf
orasSequence
can be used if laziness is desired.
Do you have your own idea for a puzzler? Submit it to 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, observe Twitter.