2016-03-16 52 views
1

我想將一個元素預先加入到數組中。我認爲我應該使用:+,但似乎這並不工作:前綴到字符串數組

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)) 

我應該如何在前面加上 「一」 給陣列( 「A」, 「B」, 「C」)

+4

'val updatedNodes =「a」+:nodes'? –

+0

這麼明顯!對於scala的'操作員'我還是不太滿意,非常感謝 –

+1

,記得簡單的規則,當操作符以':'結尾時,當你使用中綴表示法時它綁定到右邊,所以當你的參數需要在左邊對象然後方法需要以冒號結尾 –

回答

0

我認爲您想使用+:運營商:

val updatedNodes = "a" +: nodes 
1

請參閱Scala API for Array。即,

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

而且通過在一個單Array包裹串,

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

還要注意++:爲等同於與++前面加上。