I have the following Kotlin classes:
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!!))
}
}
And I have the following function:
fun handle(single: Single<String>): Single<Result> {
return single
.map { Single.Success() }
.onError { Single.Error() }
}
But onError
fails with:
Type Mismatch.
Required: Single.Success
Found: Single.Error
I realize I can work around this with:
fun handle(single: Single<String>): Single<Result> {
return single
.map { Single.Success() as Single<Result> }
.onError { Single.Error() as Single<Result> }
}
But I prefer to force type inference to work left-to-right as much as possible. That is, I'd prefer the { Single.Success() }
lambda to specify and explicit return type.
Is an explicit return type allowed in Kotlin? the functionLiteral Grammar makes it look like it can't, but I'm not an expert in reading grammars.
You actually cannot explicitly declare the return type in a Kotlin lambda:
One thing missing from the lambda expression syntax presented above is the ability to specify the return type of the function.
https://kotlinlang.org/docs/reference/lambdas.html#anonymous-functions
This worked! Someone else gave me the answer in another forum, and if they respond here, I'll mark their answer correct.
fun handle(single: Single<String>): Single<Result> {
return single
.map<Result> { Single.Success() }
.onError<Result> { Single.Error() }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With