我的代码段落在
之下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)
答案 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)