xun su
12/04/2022, 3:13 AMval return5 = {5}
I think it is equal to
fun return5(): Int {
// note return here
return 5
}
if so, please explain the code bellow:
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
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 ?
``` ```ephemient
12/04/2022, 3:41 AMephemient
12/04/2022, 3:42 AMtest(foo)
will errorVampire
12/04/2022, 3:43 AMephemient
12/04/2022, 3:43 AM{ 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 lambdaephemient
12/04/2022, 3:43 AMUnit
is special-casedephemient
12/04/2022, 3:44 AMlist.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 lambdaxun su
12/04/2022, 4:04 AMUnit
is inferred from context", in this case , "context" mean I've defined fn:()->Unit
?, @ephemientVampire
12/04/2022, 4:09 AMephemient
12/04/2022, 4:14 AMxun su
12/04/2022, 4:18 AM