为什么Kotlin高阶函数可以命名参数? [英] Why can Kotlin high order functions have named arguments?

查看:92
本文介绍了为什么Kotlin高阶函数可以命名参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们看下面的代码片段:

Let's take the following code snippet:

class Foo {
    fun bar(baz: (x: String) -> Unit) {
        // ...
    }
}

以这种方式和baz: (String) -> Unit均可正确编译(请注意,x:已在此处删除)

It compiles correctly both in that way and with baz: (String) -> Unit (note that x: has been removed here)

为什么可以将baz函数的第一个参数命名为x?可以以任何方式使用它吗?

Why is it possible to name the first argument of baz function as x? Can it be used in any way?

推荐答案

此选项是可选的,可为bar方法的调用者提供额外的含义,以使他们知道要传入的baz方法的含义.接收作为其参数.

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.

当使用Ctrl + Q查找bar方法的文档时,它将显示在IntelliJ中;如果您在传递给bar的lambda中单击Ctrl + Space,它将自动完成x ->.当然,调用者仍然可以按自己的意愿命名lambda的传入参数,但这很有用,尤其是在lambda具有多个参数的情况下.

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) {
    // ...
}

当您从自动补全中选择bar函数时,IDEA会自动为您提供此lambda正文:

IDEA will automatically give you this lambda body when you choose the bar function from autocompletion:

bar { foo1, foo2, foo3 ->

}

这篇关于为什么Kotlin高阶函数可以命名参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆