【发布时间】:2012-04-17 08:50:58
【问题描述】:
我查看了这些链接
http://blog.danielwellman.com/2008/03/using-scalas-op.html
http://blog.tmorris.net/scalaoption-cheat-sheet/
我有一张 [String, Integer] 的地图,当我执行 map.get("X") 时,我得到了一个选项。我想要以下内容。
val Int count = map.get(key);
// If the key is there I would like value if it is not I want 0
如何在一行中实现这一目标?我需要多次这样做。每次都为此编写一个函数看起来有点低效。我确信我缺少一些智能的单行怪癖,但我真的很喜欢将值转换为单行中的整数:)
【问题讨论】:
-
如果你得到一个选项,那么你有一个 Map[String, Option[Int]] 而不是 Map[String, Int]。
-
@MirkoN。不,这是因为 get 返回 Option[Value]。斯卡拉>
Map(1 -> 2).get(1)res2: Option[Int] = Some(2) -
好吧,如果
Int不可用,你会怎么做?取决于答案,最佳解决方案是不同的。