I don't understand the real difference between the curly braces and and the normal brackets in Kotlin when using RxJava. For example, I have the following code which works as expected:

someMethodThatReturnsCompletable()
    .andThen(anotherMethodThatReturnsACompletable())
    .subscribe(...)

但以下方法不起作用:

someMethodThatReturnsCompletable()
    .andThen { anotherMethodThatReturnsACompletable() }
    .subscribe(...)

请注意链的andThen()个部分与大括号的不同之处.我不明白这两者有什么不同.我看过一些文章,但不幸的是,我仍然难以理解这个细微的区别.

推荐答案

第一个代码段执行anotherMethodThatReturnsACompletable(),并将返回值传递给andThen(),其中Completable被接受为参数.

在第二个代码段中,您将函数文字写成lambda expression.它传递() -> UnitandThen()类型的函数,这也是一个有效语句,但lambda中的代码可能无法调用.

在Kotlin中,有一种约定,即如果函数的最后一个参数是函数,并且要将lambda表达式作为相应的参数传递,则可以在括号外指定它:

lock (lock) {
    sharedResource.operation()
}

Since Kotlin support SAM conversion,

这意味着,只要接口方法的参数类型与Kotlin函数的参数类型匹配,Kotlin函数文本就可以通过一个非默认方法自动转换为Java接口的实现.

Looking back to Completable, there are several overloaded andThen() functions:

andThen(CompletableSource next)
andThen(MaybeSource<T> next)
andThen(ObservableSource<T> next)
andThen(org.reactivestreams.Publisher<T> next)
andThen(SingleSource<T> next)

Here you can specify the SAM Type by calling:

andThen( CompletableSource {
    //implementations
})

Kotlin相关问答推荐

如何使用收件箱文件中的类运行Kotlin应用程序

如何在Kotlin中为两个数据类创建可重用的方法?

我如何测试一个可组合组件没有显示,但如果它不存在也接受?

如果启用了Flyway迁移,则不能具有配置属性';datources.default.架构-生成

编译后的JavaFX应用程序立即以静默方式崩溃

Microronaut Data 4和JDbi

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

从 Kotlin 的父类获取函数注解

在 Kotlin 中实现并输入 Either

Kotlin 获取继承类的默认 hashCode 实现

在kotlin中匹配多个变量

判断 Kotlin 变量是否为函数

验证构造函数中的值组合

从带有 Room 和 Flows 的 SQLite 表中获取祖先树

如何在kotlin中使用协程每秒调用一个函数

在 Kotlin 中,当枚举类实现接口时,如何解决继承的声明冲突?

TextField maxLength - Android Jetpack Compose

大小写敏感性 Kotlin / ignoreCase

如何修复未解析的参考生命周期范围?

如何在 Kotlin 中定义新的运算符?