如何正确使用Scala Hashmaps和选项?

时间:2011-08-12 22:52:02

标签: scala

我的代码段落在

之下
import scala.collection.mutable.HashMap

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

我收到以下编译错误

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

1 个答案:

答案 0 :(得分:4)

您可能希望crossingMap包含String -> Long对。然后你可以做到以下几点,

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

如果您确实希望crossingMap值的类型为Option[Long],那么您必须执行类似的操作,

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