user404345
user404345

Reputation:

Prepend to String array

I want to prepend an element to an array. I assumed I should use :+ but it seems this does not work:

scala> val nodes: Array[String] = Array("b", "c")
nodes: Array[String] = Array(b, c)

scala> val updatedNodes = "a" :+ nodes
updatedNodes: scala.collection.immutable.IndexedSeq[Any] = Vector(a, Array(b, c))

How should I prepend "a" to give Array("a", "b", "c")

Upvotes: 5

Views: 4556

Answers (2)

elm
elm

Reputation: 20435

Refer to Scala API for Array. Namely,

"a" +: xs   // prepend
xs  :+ "a"  // append

Also by wrapping the string in a singleton Array,

Array("a") ++ xs          // prepend
xs         ++ Array("a")  // append

Note also ++: as equivalent to prepending with ++.

Upvotes: 5

pedrorijo91
pedrorijo91

Reputation: 7865

I think you want to use the +: operator:

val updatedNodes = "a" +: nodes

Upvotes: 0

Related Questions