【发布时间】:2019-04-20 03:27:24
【问题描述】:
我有以下 Kotlin 类:
sealed class Result {
data class Success()
data class Failure()
}
class Single<R>(val value: R?, throwable: Throwable?) {
fun map(mapper: (R) -> T): Single<T> {
return Single(mapper(value!!), null)
}
fun onError(recover: (Throwable) -> T): Single<T> {
return Single(recover(throwable!!))
}
}
我有以下功能:
fun handle(single: Single<String>): Single<Result> {
return single
.map { Single.Success() }
.onError { Single.Error() }
}
但是onError 失败了:
Type Mismatch.
Required: Single.Success
Found: Single.Error
我意识到我可以解决这个问题:
fun handle(single: Single<String>): Single<Result> {
return single
.map { Single.Success() as Single<Result> }
.onError { Single.Error() as Single<Result> }
}
但我更喜欢强制类型推断尽可能从左到右工作。也就是说,我更喜欢 { Single.Success() } lambda 来指定和显式返回类型。
Kotlin 中是否允许显式返回类型? functionLiteral Grammar 让它看起来不能,但我不是阅读语法的专家。
【问题讨论】:
-
添加
in对您有什么帮助吗? ``` 有趣的句柄(single:Single):Single { return single .map { Result.Success() } .onError { Result.Failure() } } `` -
我不能更改
handle,所以不行。