【问题标题】:Kotlin lambda with explicit return type具有显式返回类型的 Kotlin lambda
【发布时间】: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,所以不行。

标签: lambda kotlin


【解决方案1】:

您实际上无法在 Kotlin lambda 中显式声明返回类型:

上面介绍的 lambda 表达式语法中缺少的一点是能够指定函数的返回类型。

https://kotlinlang.org/docs/reference/lambdas.html#anonymous-functions

【讨论】:

    【解决方案2】:

    这行得通!其他人在另一个论坛上给了我答案,如果他们在这里回复,我会将他们的答案标记为正确。

    fun handle(single: Single<String>): Single<Result> {
      return single
        .map<Result> { Single.Success() }
        .onError<Result> { Single.Error() }
    }
    

    【讨论】:

    猜你喜欢
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多