Appending an element to the end of a list in Scala

后端 未结 5 1398
北恋
北恋 2020-12-02 05:01

I can\'t add an element of type T into a list List[T]. I tried with myList ::= myElement but it seems it creates a strange object and

相关标签:
5条回答
  • 2020-12-02 05:23

    Lists in Scala are not designed to be modified. In fact, you can't add elements to a Scala List; it's an immutable data structure, like a Java String. What you actually do when you "add an element to a list" in Scala is to create a new List from an existing List. (Source)

    Instead of using lists for such use cases, I suggest to either use an ArrayBuffer or a ListBuffer. Those datastructures are designed to have new elements added.

    Finally, after all your operations are done, the buffer then can be converted into a list. See the following REPL example:

    scala> import scala.collection.mutable.ListBuffer
    import scala.collection.mutable.ListBuffer
    
    scala> var fruits = new ListBuffer[String]()
    fruits: scala.collection.mutable.ListBuffer[String] = ListBuffer()
    
    scala> fruits += "Apple"
    res0: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple)
    
    scala> fruits += "Banana"
    res1: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple, Banana)
    
    scala> fruits += "Orange"
    res2: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple, Banana, Orange)
    
    scala> val fruitsList = fruits.toList
    fruitsList: List[String] = List(Apple, Banana, Orange)
    
    0 讨论(0)
  • 2020-12-02 05:24

    We can append or prepend two lists or list&array
    Append:

    var l = List(1,2,3)    
    l = l :+ 4 
    Result : 1 2 3 4  
    var ar = Array(4, 5, 6)    
    for(x <- ar)    
    { l = l :+ x }  
      l.foreach(println)
    
    Result:1 2 3 4 5 6
    

    Prepending:

    var l = List[Int]()  
       for(x <- ar)  
        { l= x :: l } //prepending    
         l.foreach(println)   
    
    Result:6 5 4 1 2 3
    
    0 讨论(0)
  • 2020-12-02 05:27
    List(1,2,3) :+ 4
    
    Results in List[Int] = List(1, 2, 3, 4)
    

    Note that this operation has a complexity of O(n). If you need this operation frequently, or for long lists, consider using another data type (e.g. a ListBuffer).

    0 讨论(0)
  • 2020-12-02 05:32

    That's because you shouldn't do it (at least with an immutable list). If you really really need to append an element to the end of a data structure and this data structure really really needs to be a list and this list really really has to be immutable then do eiher this:

    (4 :: List(1,2,3).reverse).reverse
    

    or that:

    List(1,2,3) ::: List(4)
    
    0 讨论(0)
  • 2020-12-02 05:40

    This is similar to one of the answers but in different way :

    scala> val x = List(1,2,3)
    x: List[Int] = List(1, 2, 3)
    
    scala> val y = x ::: 4 :: Nil
    y: List[Int] = List(1, 2, 3, 4)
    
    0 讨论(0)
提交回复
热议问题