简体   繁体   中英

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.

...
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[]]

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

You are never actually changing the newPStat list. 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:

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:

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 :

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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