Kotlin lambda with explicit return type

Viewed 5086

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.

2 Answers

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() }
}
Related