问题
Let's take the following code snippet:
class Foo {
fun bar(baz: (x: String) -> Unit) {
// ...
}
}
It compiles correctly both in that way and with baz: (String) -> Unit
(note that x:
has been removed here)
Why is it possible to name the first argument of baz
function as x
? Can it be used in any way?
回答1:
This is optional to provide extra meaning for callers of the bar
method, to let them know what the the baz
method they're passing in will receive as their parameter.
It will show up in IntelliJ when looking up the bar
method's documentation with Ctrl + Q
, and it will autocomplete x ->
if you hit Ctrl + Space
inside the lambda passed to bar
as well. Of course callers can still name the incoming parameter of the lambda however they'd like, but this can be useful especially if the lambda has multiple parameters.
For example, with this higher order function:
fun bar(foo: (foo1: Int, foo2: Int, foo3: Int) -> Unit) {
// ...
}
IDEA will automatically give you this lambda body when you choose the bar
function from autocompletion:
bar { foo1, foo2, foo3 ->
}
来源:https://stackoverflow.com/questions/48834273/why-can-kotlin-high-order-functions-have-named-arguments