https://kotlinlang.org logo
Title
n

Narayan Iyer

11/28/2018, 4:49 PM
So, when I write my tail function like so:
fun <T> tail(ls: List<T>): List<T> {
   return ls.drop(1)
}
why is it insisting on the
return
statement?!
c

Casey Brooks

11/28/2018, 4:52 PM
returns are required for function definitions. Lambdas cannot have `return`s because the last expression is implicitly returned.
Note that Kotlin is not a functional programming language, it is primarily OOP imperative. It just has some FP constructs, but it does not require you use them. It is much closer to Java than to Scala
if you want the last value returned from a function definition, assign to it the expression or a lambda
fun <T> tail(ls: List<T>) = {
    ls.drop(1)
}
or
fun <T> tail(ls: List<T>) = ls.drop(1)
n

Narayan Iyer

11/28/2018, 4:57 PM
Seems like there is a difference between the above two code!
>>> fun <T> tail(ls: List<T>) = {
...   ls.drop(1)
... }
>>> tail(listOf(4,3,2,1))
() -> kotlin.collections.List<T>
>>> fun <T> tail(ls: List<T>): List<T> = ls.drop(1)
>>> tail(listOf(4,3,2,1))
[3, 2, 1]
>>>
I get it, because the first definition would be a lambda ... and hence a function is returned, whereas in the latter, it is executed!
c

Casey Brooks

11/28/2018, 5:02 PM
Ah, you’re right, my bad. I didn’t actually run it. Use the
run
function to invoke the lambda immediately and get the correct return type:
fun <T> tail(ls: List<T>) = run {
    ls.drop(1)
}
You could also just invoke the lambda directly, but that’s not idiomatic Kotlin. The normal way to do it is to use a function that invokes a lambda as the function expression
s

SiebelsTim

11/28/2018, 5:09 PM
The lambda and run are unnecessary if you only have one statement. Simply:
fun <T> tail(ls: List<T>) = ls.drop(1)
n

Narayan Iyer

11/28/2018, 5:30 PM
Yes, we had discussed that