android - 在 Kotlin 中传递和使用函数作为构造函数参数

标签 android kotlin

如何创建一个将函数作为构造函数参数的类。然后,在稍后的类(class)中使用这个函数。

最佳答案

您可以像使用任何其他类型一样拥有具有函数类型的属性:

class A(val f: () -> Unit) {

    fun foo() {
        f()
    }

}

从这里,您可以将该函数作为方法引用传递给构造函数:

fun bar() {
    println("this is bar")
}

val a = A(::bar)
a.foo()             // this is bar

或作为 lambda:

val a = A({ println("this is the lambda") })

您甚至可以为作为函数的最后一个参数的 lambda 做通常的语法糖(虽然这有点疯狂):

val a = A { println("this is the lambda") }

关于android - 在 Kotlin 中传递和使用函数作为构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44912803/

相关文章:

android - IntelliJ 和 android.support.v7.widget.GridLayout

java - 如何将 csv 文件截断为 n 行而不读取整个文件

android - 如何在 Kotlin Android 的 DatePicker 中禁用 future 日期

android - UNINITIALIZED VARIABLE 必须初始化变量 _longPressed

android-studio - 从 Intellij Idea 中的自动完成和自动导入中排除 kotlin.Result

android - Beginning Android Games 书中的代码给出错误

javascript - 为什么 android webView 不支持 webSocket?

android - 在android中如何清除CharSequence中的元素?

android - 如何让 Phonegap 应用程序在 Android 上接收变量?

java - Android https 请求奇怪失败