I have the following bit of code in my HomeActivity to use LiveData.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    // Show the launch splash screen.
    //
    this.setContentView(R.layout.activity_home)

    this.viewModel = ViewModelProviders.of(this).get(HomeViewModel::class.java)

    this.viewModel.getUser().observe(this, Observer { user: User? ->

    });

}

While this seems to work, what does the following part mean?

Observer { user: User? ->

}

这必须产生一个符合Observer接口的对象,该对象具有

void onChanged (T t)

https://developer.android.com/reference/android/arch/lifecycle/Observer.html

How does

Observer { user: User? ->

}

result in an object with an onChanged method?

I don't know what putting the name of an interface in front of a lambda expression means.

Thanks!

推荐答案

这称为SAM Conversion,这是一个有助于与Java Single Abstract Method接口交互的概念,如您的示例所示.

下面创建了Runnable的一个实现,其中单个抽象方法是run():

val runnable = Runnable { println("This runs in a runnable") }

文档中有描述:https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions

或者,但更详细的是,可以使用object:

val runnable2 = object : Runnable {
        override fun run() {
            println("This runs in a runnable")
        }
}

这两个都是interface的匿名实现的例子.当然,也可以创建一个具体的子类,然后实例化它.

class MyRunnable : Runnable {
    override fun run() {
        println("This runs in a runnable")
    }
}

val runnable3 = MyRunnable()

Kotlin相关问答推荐

如何检测一个值是否是Kotlin中的枚举实例?

Webpack 配置未应用于 kotlin 多平台react 项目

为什么会出现Kotlin.Unit错误以及如何修复它?

为什么 trySend 会发出假数据?

如何使用函数类型或 lambdas 作为 Kotlin 上下文接收器的类型?

如何在 kotlin 中创建自定义迭代器并添加到现有类?

Eclipse:无法安装 Kotlin 插件

顶级属性的初始化

kotest 更改环境变量

如果不为空,则为 builder 设置一个值 - Kotlin

Kotlin 中二叉树的深度

runBlocking 中的 deferred.await() 抛出的异常即使在被捕获后也被视为未处理

在 Kotlin 中使用 @Parcelize 注释时如何忽略字段

Kotlin 静态函数:伴生对象,@JvmStatic @JvmField

在构造函数中仅注入某些参数

带有迭代器函数的 Kotlin 无限序列

Kotlin 创建snackbar

Kotlin如何分派invoke操作符?

可以在函数参数中使用解构吗?

为什么 Kotlin 会收到这样的 UndeclaredThrowableException 而不是 ParseException?