开发者

How do I use Scala Hashmaps and Options together correctly?

开发者 https://www.devze.com 2023-03-28 00:38 出处:网络
My code snippets are below import scala.collection.mutable.HashMap val crossingMap = new HashMap[String, Option[Long]]

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

精彩评论

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