I'm confused about something. In many places the c...
# announcements
e
I'm confused about something. In many places the compiler just returns the last thing of a scope, like in lambdas, but sometimes I'm asked to return explicitly by the compiler. What's the rule for returning the last thing in the scope vs requiring an explicit return?
It seems like functions always require the return
n
I think lambda = implicit return, function = explicit return
e
Copy code
fun something(num: Int) : Int {
	num + 1
}

fun main() {
    println("Hello, world!!! ${something(1)}")
}
A 'return' expression required in a function with a block body
n
or maybe not even lambda, but like...a block. even
if
has a value.
e
I see, seems idiosyncratic ...
n
I guess
mainly you want
foo?.let { doSomething(it) }
and have that have a value
but functions are a whole...execution scope. I dunno
e
howerver:
n
return@
syntax is better in that it's not exactly a return 😄
e
Copy code
fun main() {
    val something : (num: Int) -> Int = { num ->
	  num + 1
    }
    println("Hello, world!!! ${something(1)}")
}
n
it's still not a function
e
so yeah it seems like explicit
fun ###
will always require a
return
n
if we're looking for apparent contradictions, I think you can say
Copy code
fun addOne(num: Int): Int = run {
  num + 1
}
😛
🤯 1
e
please no! 😛 haha
n
I think the reasoning is that basically Kotlin wants lbdas to be concise very badly
Omitting return is key to that
Now, some functional languages don't have return statements at all
But, early returns in longer functions are widely considered really useful and practical
Also really nice in all this is the fact that a lambda passed to an inline function can still return the outer most function
It's a big part of what makes Kotlin DSLs feel like DSLs
Or not even DSLs, just what makes the language so nice to extend with functions taking lambdas. You don't really need to care that you're passing a lambda. It's almost like adding keywords
Anyway I guess just pointing out the reasons and why it all works out nicely, maybe it will seem less idiosyncratic :-). Labelled returns are nice as well.
👍 1
s
@nanodeath that is not a contradiction, just a little ambiguous if you suggest so
n
was just messin' around 😛
e
thx @Nir that does make a lot of sense