Scala [SOLVED]: Appending to Seq in Scala

Scala [SOLVED]: Appending to Seq in Scala

Home Forums Frameworks Scala Scala [SOLVED]: Appending to Seq in Scala

Tagged: 

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #113167

    Cloudy Point
    Keymaster

    QuestionQuestion

    The following code is supposed to append to a Seq, but it prints an empty list, what’s wrong here?

    object AppendToSeq extends App{
    
        val x = Seq[Int]()
    
        x :+ 1
        x :+ 2
    
        println(x)
    
    }
    

    #113168

    Cloudy Point
    Keymaster

    Accepted AnswerAnswer

    the value x created is an immutable Sequence and the method :+ defined on the immutable sequence return a new Seq object.

    so your code should have x has a var (a mutable variable) and it should have its value re-assigned after each append (:+) operation as shown below.

    scala> var x = Seq[Int]()
    x: Seq[Int] = List()
    
    scala> x = x :+ 1
    x: Seq[Int] = List(1)
    
    scala> x = x :+ 2
    x: Seq[Int] = List(1, 2)
    
    scala> x
    res2: Seq[Int] = List(1, 2)
    

    Source: https://stackoverflow.com/questions/43992716/appending-to-seq-in-scala
    Author: rogue-one
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.