我见过函数具有由ClassName.()指定的参数的示例 这似乎不是扩展函数,它是ClassName.Function()

例如Kotterknife:

private val View.viewFinder: View.(Int) -> View?
    get() = { findViewById(it) }

Which I don't quite know the function of,

还有MaterialDrawerKt

fun Activity.drawer(setup: DrawerBuilderKt.() -> Unit = {}): Drawer {
    val builder = DrawerBuilderKt(this)
    builder.setup()
    return builder.build()
}

Where the code allows you to directly call

drawer {
    ...
}

rather than give it arguments surrounded by the parentheses.

有关于这个的文件吗?

推荐答案

A function that takes in nothing and returns nothing in Kotlin looks like:

var function : () -> Unit

The difference is that the function in your code takes in nothing, returns nothing, but is invoked on an object.

例如

class Builder (val multiplier: Int) {

    fun invokeStuff(action: (Builder.() -> Unit)) {
        this.action()
    }

    fun multiply(value: Int) : Int {
        return value * multiplier
    }
}

这里重要的一点是我们宣布"行动"类型的方式

action: (Builder.() -> Unit)

这是一个不返回任何内容、不接受任何内容但在"Builder"类型的对象上调用的函数.

Refer more here.

Kotlin相关问答推荐

计算值的Elvis算子

我需要后台工作才能使用卡夫卡的消息吗?

S使用MAP和ElseThrow的习惯用法是什么?

列表在 android WebView 中没有正确迭代

具有泛型类型的 Kotlin 密封接口不会为其子类型推断约束

Kotlin 插件之间的区别

如何将jooq multiset的结果映射到Hashmap(Java Map)?

`this@classname` 在 Kotlin 中是什么意思?

以编程方式重新启动 Spring Boot 应用程序/刷新 Spring 上下文

无法为 retrofit2.Call 调用无参数构造函数

如何在MVVM架构中观察RecyclerView适配器中的LiveData?

Kotlin通过映射委托属性,如果映射中不存在,则抛出NoTouchElementException

Kotlin/JS,Gradle 插件:无法加载@webpack-cli/serve命令

如何在 Jetpack Compose 的 LazyColumn/LazyRow 中禁用和启用滚动?

Kotlin中OnclickListener方法之间的差异

在kotlin中初始化类变量的正确位置是什么

android Room 将 Null 作为非 Null 类型返回

在 Kotlin 中返回函数有不那么丑陋的方法吗?

Kotlin 是否支持部分应用程序?

Kotlin反射不可用