Reputation:
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
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
Reputation: 7865
I think you want to use the +:
operator:
val updatedNodes = "a" +: nodes
Upvotes: 0