Add element to a list In Scala

后端 未结 4 490
旧时难觅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:37

    Since you want to append elements to existing list, you can use var List[Int] and then keep on adding elements to the same list. Note -> You have to make sure that you insert an element into existing list as follows:-

    var l: List[int] = List() // creates an empty list

    l = 3 :: l // adds 3 to the head of the list

    l = 4 :: l // makes int 4 as the head of the list

    // Now when you will print l, you will see two elements in the list ( 4, 3)

提交回复
热议问题