Int plus-plus

fun main(args: Array<String>) {

var i = 0

println(i.inc())

println(i.inc())



var j = 0

println(j++)

println(++j)

}

Author: Dmitry Kandalov

What will it display? Some possibilities:

a) 0, 1, 0, 1

b) 0, 1, 0, 2

c) 1, 1, 0, 2

d) 1, 2, 0, 1

Check out the answer and an explanation using this link or by reading this article till the end.

Return in function literal

fun f1() {

(1..4).forEach {

if (it == 2) return

print(it)

}

}



fun f2() {

(1..4).forEach(fun(it) {

if (it == 2) return

print(it)

})

}



fun main(args: Array<String>) {

f1()

f2()

}

Author: Marcin Moskala

What will it display? Some possibilities:

a) 134134

b) 1134

c) 1341

d) Doesn’t compile

Check out the answer and an explanation using this link or by reading this article till the end.

WTF with labels

fun main(args: Array<String>) {

val j = wtf@{ n: Int -> wtf@(wtf@n + wtf@2) }(10)

print(j)

}

Author: Dmitry Kandalov

What will it display? Some possibilities:

a) It won’t compile

b) 10

c) 2

d) 12

Check out the answer and an explanation using this link or by reading this article till the end.

Answers and explanations

For “Int plus-plus” the correct answer is:

c) 1, 1, 0, 2

Why? Here is an explanation:

The answer is as expected since C++. ++ operator in prefix position (++j) increment the number and returns the new value, and is a suffix position it also increments property but returns the previous value. The tricky part is that both prefix and suffix for reference to Kotlin function inc . This is why it is not so clear. Although Kotlin has special support for prefix position that is described in the documentation: https://kotlinlang.org/docs/reference/operator-overloading.html#increments-and-decrements

For “Return in function literal” the correct answer is:

b) 1134

Why? Here is an explanation:

When we want to use return in a lambda expression, we need to use a label like return@forEach . Otherwise, it will not be accepted. Here since for-each is inline function and allows non-local return, this return finishes f1 function.

For “WTF with labels” the correct answer is:

d) 12

Why? Here is an explanation: