简体   繁体   English

如何将对象从Vector添加到Scala中的ListBuffer?

[英]How to Add Objects from Vector to ListBuffer in Scala?

I am not Able to Print newPStat List's Elements on console, After doing following simple transformation, Its damn Simple and Still I am missing some very non trivial thing. 我不能够在控制台上打印newPStat List的Elements,完成简单的转换之后,该死的Simple和Still我仍然缺少一些非常琐碎的东西。

...
val newPStat = List[PSObject]()

S1ServiceObject.getPS.onComplete({
        case Success(pSList) => {
          logger.info("Number of Ps - " + pSList.size)
            pSList.foreach{
              pfS => {
              newPStat ++ List(new PSObject(pfS.pfNameRemote, pfS.impRemote,
                  pfS.actCRemote, pfS.actARemote) )
                println("prx Size "+newPStat.size)
              }
            }
          }
        case Failure(exception) => {
          logger.error("Error while trying to get PS  - " + exception.getMessage)
        }
      })


case class PSObject(pfName: String, imp : BigDecimal, actC: Int, actA: Int)

// printing the object's elements

newPStat.foreach{x => println("prax: "+x.toString)}

As you can see above function calls 如您所见,上面的函数调用
Following Function, which is a Service layer Func. 跟随功能,是服务层功能。 which Returns Future[Vector[]] 返回未来[Vector []]

def getPS: Future[Vector[PSObjectDTO]]= {
    getPSData
  }

You are never actually changing the newPStat list. 您实际上从未更改过newPStat列表。 This line in fact does nothing: 该行实际上不执行任何操作:

newPStat ++ List(new PSObject(pfS.pfNameRemote, pfS.impRemote, pfS.actCRemote, pfS.actARemote) )

You are making a new list but never assign it to anything, as shown by this REPL example: 您正在制作一个新列表,但从未将其分配给任何内容,如以下REPL示例所示:

scala> val a = List(1,2,3)
a: List[Int] = List(1, 2, 3)

scala> a ++ List(4)
res9: List[Int] = List(1, 2, 3, 4)

scala> a
res10: List[Int] = List(1, 2, 3)

So you will need to change newPStat from val to var and reassign it to the new list: 因此,您需要将newPStatval更改为var并将其重新分配到新列表:

newPStat = newPStat ++ List(new PSObject(pfS.pfNameRemote, pfS.impRemote, pfS.actCRemote, pfS.actARemote) )

Also since you are dynamically building a list, I would instead reccomend an ArrayBuffer : 另外,由于您是动态构建列表,因此我建议使用ArrayBuffer

scala> val a = collection.mutable.ArrayBuffer.empty[Int]
a: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()

scala> a.append(1)

scala> a.append(2)

scala> a.toArray
res13: Array[Int] = Array(1, 2)

A more idiomatic approach would be to use a map instead of a foreach : 更加惯用的方法是使用map而不是foreach

newPStat = pSList.map{pfS => new PSObject(pfS.pfNameRemote, pfS.impRemote, pfS.actCRemote, pfS.actARemote)}.toList

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

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