Hi, I'm a little confused about lambda expression....
# getting-started
x
Hi, I'm a little confused about lambda expression. say we have a expression below
Copy code
val return5 = {5}
I think it is equal to
Copy code
fun return5(): Int {
  // note return here
  return 5
}
if so, please explain the code bellow:
Copy code
fun test(fn: () -> Unit) {}

val foo =
    fun(name: String): String {
      return name
    }

test { foo } // why no error ?
I mean ,
test
accept a parameter , which is a function with the type
()->Unit
, but I think
test { foo }
is equals to
Copy code
test(
      fun() {
        return foo
      })
Apparently it mismatch the type of parameter
fn
of the function
test
, the case above is
() -> String -> String
, but why no error here ? ``` ```
e
they are not completely equal
as for your second question:
Copy code
test(foo)
will error
v
If the method you implement using the lambda requires a return value, the last expression in the lambda is used as the return value. If the method does not have a return value, it just also works.
e
when you write
{ foo }
, it doesn't actually mean `fun() { return foo }`: because the return type of
Unit
is inferred from context, Kotlin ignores the type of the last value of the lambda
Unit
is special-cased
otherwise writing functions like
Copy code
list.forEach { item -> otherList.add(item) }
would be very annoying to write, because
add
returns a
Boolean
while
forEach
doesn't want any result from its lambda
x
"because the return type of
Unit
is inferred from context", in this case , "context" mean I've defined
fn:()->Unit
?, @ephemient
v
Yes
x
thank you all! really appreciate it!😀
👌 1