Why can Kotlin high order functions have named arguments?

我是研究僧i 提交于 2021-01-28 09:20:42

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!