Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Scala Hashmaps and Options together correctly?

Tags:

scala

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 the following compile error

error: type mismatch;
found   : Any
required: Long
val time: Long = crossingMap.get(crossingData).getOrElse(0)
like image 626
deltanovember Avatar asked Aug 12 '11 22:08

deltanovember


People also ask

How does HashMap work in Scala?

HashMap is a part of Scala Collection's. It is used to store element and return a map. A HashMap is a combination of key and value pairs which are stored using a Hash Table data structure. It provides the basic implementation of Map.

How do you store a value on a map?

a) The values can be stored in a map by forming a key-value pair. The value can be retrieved using the key by passing it to the correct method. b) If no element exists in the Map, it will throw a 'NoSuchElementException'. c) HashMap stores only object references.


1 Answers

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)
like image 172
Kipton Barros Avatar answered Oct 13 '22 01:10

Kipton Barros