Scala: what is the best way to append an element to an Array?

后端 未结 3 1730
你的背包
你的背包 2021-01-29 21:34

Say I have an Array[Int] like

val array = Array( 1, 2, 3 )

Now I would like to append an element to the array, say the value

3条回答
  •  后悔当初
    2021-01-29 22:00

    val array2 = array :+ 4
    //Array(1, 2, 3, 4)
    

    Works also "reversed":

    val array2 = 4 +: array
    Array(4, 1, 2, 3)
    

    There is also an "in-place" version:

    var array = Array( 1, 2, 3 )
    array +:= 4
    //Array(4, 1, 2, 3)
    array :+= 0
    //Array(4, 1, 2, 3, 0)
    

提交回复
热议问题