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: