Appending an element to the end of a list in Scala

后端 未结 5 1420
北恋
北恋 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: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
    

提交回复
热议问题