Add element to a list In Scala

后端 未结 4 491
旧时难觅i
旧时难觅i 2020-12-03 01:04

I\'m running Scala 2.10.2. I want to create a list, then add some elements to the list and expect to see all the elements in the lists when I call the list\'s name. But I ob

4条回答
  •  执笔经年
    2020-12-03 01:19

    You are using an immutable list. The operations on the List return a new List. The old List remains unchanged. This can be very useful if another class / method holds a reference to the original collection and is relying on it remaining unchanged. You can either use different named vals as in

    val myList1 = 1.0 :: 5.5 :: Nil 
    val myList2 = 2.2 :: 3.7 :: mylist1
    

    or use a var as in

    var myList = 1.0 :: 5.5 :: Nil 
    myList :::= List(2.2, 3.7)
    

    This is equivalent syntax for:

    myList = myList.:::(List(2.2, 3.7))
    

    Or you could use one of the mutable collections such as

    val myList = scala.collection.mutable.MutableList(1.0, 5.5)
    myList.++=(List(2.2, 3.7))
    

    Not to be confused with the following that does not modify the original mutable List, but returns a new value:

    myList.++:(List(2.2, 3.7))
    

    However you should only use mutable collections in performance critical code. Immutable collections are much easier to reason about and use. One big advantage is that immutable List and scala.collection.immutable.Vector are Covariant. Don't worry if that doesn't mean anything to you yet. The advantage of it is you can use it without fully understanding it. Hence the collection you were using by default is actually scala.collection.immutable.List its just imported for you automatically.

    I tend to use List as my default collection. From 2.12.6 Seq defaults to immutable Seq prior to this it defaulted to immutable.

提交回复
热议问题