So, when I write my tail function like so: ``` fun...
# getting-started
n
So, when I write my tail function like so:
Copy code
fun <T> tail(ls: List<T>): List<T> {
   return ls.drop(1)
}
why is it insisting on the
return
statement?!
c
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
Copy code
fun <T> tail(ls: List<T>) = {
    ls.drop(1)
}
or
Copy code
fun <T> tail(ls: List<T>) = ls.drop(1)
n
Seems like there is a difference between the above two code!
Copy 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
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:
Copy code
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
The lambda and run are unnecessary if you only have one statement. Simply:
fun <T> tail(ls: List<T>) = ls.drop(1)
n
Yes, we had discussed that