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

后端 未结 3 1729
你的背包
你的背包 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 21:59

    The easiest might be:

    Array(1, 2, 3) :+ 4
    

    Actually, Array can be implcitly transformed in a WrappedArray

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2021-01-29 22:06

    You can use :+ to append element to array and +: to prepend it:

    0 +: array :+ 4
    

    should produce:

    res3: Array[Int] = Array(0, 1, 2, 3, 4)
    

    It's the same as with any other implementation of Seq.

    0 讨论(0)
提交回复
热议问题