简体   繁体   English

Scala列表打印问题 - IntelliJ IDEA

[英]Scala list print issue — IntelliJ IDEA

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 在IntelliJ IDEA中运行上面的代码给出了类似于以下输出的内容

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 从REPL运行类似的代码可以得到预期的输出

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 addValue method you write nodes + (uuid -> (value :: (nodes get uuid getOrElse Nil))) which does not change the list in nodes , but only creates a new copy with the value added. 在你的addValue方法中你编写nodes + (uuid -> (value :: (nodes get uuid getOrElse Nil)))这不会改变nodes的列表,但只创建一个添加了值的新副本。 Since Map is immutable by default you'll have to store it like you do with the = -sign in the addNode method. 由于默认情况下Map是不可变的,因此您必须像在addNode方法中使用= -sign一样存储它。

The reason it prints anything at all is because the first entry consists of a UUID (String) and Nil (empty List). 它打印任何东西的原因是因为第一个条目包含UUID(String)和Nil(空List)。 The "8b2b4a7b-3e65-4de0-9035-8ee1d2910983" makes sense then because it's the UUID. “8b2b4a7b-3e65-4de0-9035-8ee1d2910983”之所以有意义,是因为它是UUID。 The "List()" is a result of printing Nil (since it is an empty List). “List()”是打印Nil的结果(因为它是一个空列表)。

And there you have it. 你有它。 Try writing node += ... in the addValue in stead. 尝试在addValue中编写node += ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM