Scala 将 Option 转换为 Int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10188037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala convert Option to an Int
提问by Kannan Ekanath
I have looked at these links
我看过这些链接
http://blog.danielwellman.com/2008/03/using-scalas-op.html
http://blog.danielwellman.com/2008/03/using-scalas-op.html
http://blog.tmorris.net/scalaoption-cheat-sheet/
http://blog.tmorris.net/scalaoption-cheat-sheet/
I have a map of [String, Integer] and when I do a map.get("X") I get an option. I would like the following.
我有一个 [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
How do I achieve this in one line? I need to do this several times. It looks a bit inefficient to write a function everytime for doing this. I am sure there is some intelligent one line quirk that I am missing but I really like to get the value into an integer in ONE line :)
我如何在一行中实现这一目标?我需要这样做几次。每次都写一个函数来做这件事看起来有点低效。我确信有一些我缺少的智能单行怪癖,但我真的很喜欢将值转换为单行中的整数:)
回答by om-nom-nom
Just use getOrElse method:
只需使用 getOrElse 方法:
val count: Int = map.getOrElse(key,0);
Note also, that in Scala you write type aftername, not before.
另请注意,在 Scala 中,您在名称之后而不是之前编写类型。
回答by virtualeyes
@om-nom-nom (classic screen name) has the correct answer, but in the interest of providing yet another way™
@om-nom-nom(经典网名)有正确答案,但为了提供另一种方式™
val count = map.get(key) fold(0)(num => num)
Before in-the-know users bash me with, "Option has no fold!", fold has been added to Optionin Scala 2.10
之前最知道用户来砸我,“选项没有折!”,折已添加到选项在斯卡拉2.10
getOrElse is of course better in the current case, but in some Some/None scenarios it may be interesting to 1-liner with fold like so (edited complements of @Debiliski who tested against latest 2.10 snapshot):
getOrElse 在当前情况下当然更好,但在某些 Some/None 场景中,像这样 fold 的 1-liner 可能很有趣(@Debiliski 的编辑补充,针对最新的 2.10 快照进行了测试):
val count = map.get(k).fold(0)(dao.userlog.count(_))
I suppose in 2.9.2 and under we can already do:
我想在 2.9.2 及以下我们已经可以做到:
val count = map get(k) map ( dao.userlog.count(_) ) getOrElse(0)
Which is to say, in Scala there is often more than one way to do the same thing: in the linked thread, the OP shows more than 10 alternative means to achieve Option fold ;-)
也就是说,在 Scala 中,通常有不止一种方法可以做同样的事情:在链接线程中,OP 显示了 10 多种实现 Option 折叠的替代方法;-)
回答by missingfaktor
Yet another way.
又一种方式。
import scalaz._, Scalaz._
scala> val m = Map(9 -> 33)
m: scala.collection.immutable.Map[Int,Int] = Map(9 -> 33)
scala> m.get(9).orZero
res3: Int = 33
scala> m.get(8).orZero
res4: Int = 0

