我在使用Kotlin和RxJava的Android应用程序中遇到了一个问题.下面介绍.
import rx.Observable
data class TestUser(val name: String)
fun getTestUser(): Observable<TestUser> {
return Observable.just(TestUser("Brian")).flatMap { getUser() } // this compiles
}
fun getTestUser2(): Observable<TestUser> {
val observable = Observable.just(TestUser("Brian")).flatMap { getUser() }
return observable // this does not compile
}
fun getUser(): Observable<TestUser?> {
return Observable.just(null)
}
In getTestUser2
, the compiler infers the final return type as Observable<TestUser?>
and doesn't compile. However in getTestUser
the code does compile, and when it's run, any subscriber to that observable may be in for a surprise when the TestUser
comes back null
.
I'm guessing it's something to do with going back and forth between Kotlin and Java. But, the fact that the compiler can see the difference in getTestUser2
makes me think this could be fixable.
编辑
这是昨天(2016年2月15日)发布的最终版本Kotlin 1.0.