ran into something a bit weird and was wondering i...
# getting-started
p
ran into something a bit weird and was wondering if anyone could clear it up for me:
Copy code
list.map {
  if (condition) {
    42
  }
  0 
}
I am used to not doing else branches in Java when not needed but it seems like here I get a list of zeros if I don't put the 0 into an else branch. 🤔 Has this bitten anyone before?
b
The last line within the map lambda is what you’re returning as the result. So your example will always result a list of zeros. `if`s in kotlin are expressions; in this example your throwing away the result.
d
I struggled with this for days. Only the very last expression in the block is returned. So, with the else branch, the if expression is the last expression but without the else branch, 0 is the last expression.
p
i see.. thanks!
b
I tweaked your example @poohbar:
Copy code
fun main() {
  val list = listOf(1,2,3,4,5)

  val result = list.map {
    if (it and 1 == 0) {
      42
    } else {
      0
    }
  }
  println(result)
}
Now it returns
[0, 42, 0, 42, 0]
p
yeah i figured it out, was just wondering about "why"
b
It’s a common practice in FP languages to use the last expression of a function as the return value. Saves typing, I guess
b
almost any function has a return
so if you do:
if (condition) { log.somethingabout(it) } 0 log.somethingabout would return
which is not what you want here
j
Yeah I was bitten by this, would be nice to get some warning at least. Also you can't put explicit return there so only way is to remember put else there
a
You can do a labelled return e.g.
return@map
(https://kotlinlang.org/docs/reference/returns.html#return-at-labels)
b
Totally forgot about those. Thanks.
h
Watch the Kotlin Puzzlers from KotlinConf '17 & '18, helps a lot wrapping your head around the weirdnes that kotlin can offer 😉