【发布时间】:2020-01-20 23:51:06
【问题描述】:
给定 Scala 中的一个 Map,我想尝试第一个键,如果找不到,请尝试不同的键,如果再次找不到,则返回 None。以下按预期工作:
val scores: Map[String, Int] = Map("Alice" -> 10, "Bob" -> 3)
val singleGet: Option[Int] = scores.get("NotAKey")
println(singleGet) // None
val doubleGet = scores.getOrElse("NotAKey", scores.get("NotAKeyAgain")) // works ok if no type
println(doubleGet) // None
但如果我为 doubleGet 输入一个类型,则会出错:
val doubleGet: Option[Int] = scores.getOrElse("NotAKey", scores.get("NotAKeyAgain")) // ERROR
“Any 类型的表达式不符合预期的 Option[Int] 类型”
那么最好的方法是什么?
【问题讨论】:
-
val doubleGet: Option[Int] = scores.get("NotAKey") orElse scores.get("NotAKeyAgain"). -
@LuisMiguelMejíaSuárez 啊,谢谢!你能把它作为答案让我标记它吗?