【问题标题】:Kotlin: Type mismatch: inferred type is String? but String was expectedKotlin:类型不匹配:推断类型是字符串?但字符串是预期的
【发布时间】:2021-07-20 16:56:46
【问题描述】:

同一文件和同一行出现以下错误。

Type mismatch: inferred type is String? but String was expected
Type mismatch: inferred type is String? but TypeVariable(V) was expected

这是代码:

return posLevelRealizedFxGlRecords.filter {
      if (it == null) {
        false
      } else {
        var bookCurrency: String? = bookIdToBookCurrencyMap.getOrPut(it.bookId) {
          val book: Book? = dataLookupService.getBook(it.bookId, knowledgeTimestamp)
          book?.p?.bookCurrencyId
        }

        if (bookCurrency == null) {
          false
        } else {
          it.currencyId != bookCurrency
        }
      }
    }

在下面一行显示这些错误。

book?.p?.bookCurrencyId

我也尝试了下面的代码而不是上面的代码,

if (book == null) {
            null
          } else {
            book.p.bookCurrencyId
          }

您能帮忙解决这些错误吗?

【问题讨论】:

  • bookIdToBookCurrencyMap的类型是什么?
  • 如果book 为空,您的过滤器应该返回什么? (或者如果book.p 为空,如果可能的话?  还是book.p.bookCurrencyId?)
  • 如果 book 为 null,它应该返回 null。 book.p null 是不可能的。
  • @Nitrodon 它是 mutableMapOf()
  • 如果getOrPut() 在映射中没有找到该键,它会调用 lambda 来获取默认值并在映射中设置该值。但是您的地图具有不可为空的值,那么它如何设置为空呢?

标签: kotlin


【解决方案1】:

查看getOrPut 签名,defaultValue 参数在您的情况下应该返回一个String,但您返回一个可为空的String (String?),因此会出现编译错误。

您应该将bookIdToBookCurrencyMap 更改为mutableMapOf<String, String?> 或返回一个不可为空的String,例如:

....
book?.p?.bookCurrencyId?:"NOT_FOUND" // you can return whatever you want to express null value for bookCurrencyId
....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 2022-11-14
    • 2021-09-29
    • 2021-11-04
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    相关资源
    最近更新 更多