I have the following code
object DispatchLibrary
{
private var nodes = Map.empty[java.util.UUID, List[BigInt]]
def addNode(uuid: java.util.UUID) = if(nodes contains uuid) nodes else (nodes += (uuid -> Nil))
def addValue(uuid: java.util.UUID, value: BigInt) = nodes + (uuid -> (value :: (nodes get uuid getOrElse Nil)))
//def getValue(uuid: java.util.UUID) : List[BigInt] = ???
//def getValues() : List[BigInt] = ???
def calculated(): Boolean = !nodes.exists(_._1 eq null)
def main(args: Array[String]) : Unit =
{
val uuid = java.util.UUID.randomUUID()
addNode(uuid)
addValue(uuid, BigInt(999))
addValue(uuid, BigInt(9999))
nodes foreach {case (key, value) => println (key + "->" + value)}
}
}
Running the above code in IntelliJ IDEA gives something similar to the following output
8b2b4a7b-3e65-4de0-9035-8ee1d2910983->List()
I am not sure why the List is not being printed.
Running a similar code from the REPL gives the expected output
scala> var nodes = Map.empty[Int, List[BigInt]]
nodes: scala.collection.immutable.Map[Int,List[BigInt]] = Map()
scala> nodes += (1->Nil)
scala> nodes += (1 -> (BigInt(999) :: (nodes get 1 getOrElse Nil)))
scala> nodes += (1 -> (BigInt(9999) :: (nodes get 1 getOrElse Nil)))
scala> nodes foreach {case (key, value) => println (key + "-->" + value )}
1-->List(9999, 999)
I would appreciate also if you could help me in writing the commented methods.
In your
addValuemethod you writenodes + (uuid -> (value :: (nodes get uuid getOrElse Nil)))which does not change the list innodes, but only creates a new copy with the value added. SinceMapis immutable by default you’ll have to store it like you do with the=-sign in theaddNodemethod.The reason it prints anything at all is because the first entry consists of a UUID (String) and Nil (empty List). The “8b2b4a7b-3e65-4de0-9035-8ee1d2910983” makes sense then because it’s the UUID. The “List()” is a result of printing Nil (since it is an empty List).
And there you have it. Try writing
node += ...in theaddValuein stead.