开发者

How do I use Scala Hashmaps and Options together correctly?

My code snippets are below

import scala.collection.mutable.HashMap

val crossingMap = new HashMap[String, Option[Long]]
val crossingData: String = ...
val time: Long = crossingMap.get(crossingData).getOrElse(0)

I get t开发者_StackOverflow中文版he following compile error

error: type mismatch;
found   : Any
required: Long
val time: Long = crossingMap.get(crossingData).getOrElse(0)


You might want crossingMap to contain String -> Long pairs. Then you can do the following,

val crossingMap = new HashMap[String, Long]
val crossingData: String = ""
val time: Long = crossingMap.getOrElse(crossingData, 0)

If you really do want the crossingMap values to have type Option[Long], then you'll have to do something like,

val crossingMap = new HashMap[String, Option[Long]]
val crossingData: String = ""
val time: Long = crossingMap.getOrElse(crossingData, None).getOrElse(0)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜