Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding value to arrays in scala

Tags:

arrays

add

scala

I faced a problem where I needed to add a new value in the middle of an Array (i.e. make a copy of the original array and replace that with the new one). I successfully solved my problem, but I was wondering whether there were other methods to do this without changing the array to buffer for a while.

val original = Array(0, 1, 3, 4)
val parts = original.splitAt(2)
val modified = parts._1 ++ (2 +: parts._2)

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

What I don't like on my solution is the parts variable; I'd prefer not using an intermediate step like that. Is that the easiest way to add the value or is there some better ways to do add an element?

like image 824
Duzzz Avatar asked Dec 10 '22 17:12

Duzzz


1 Answers

This is precisely what patch does:

val original = Array(0, 1, 3, 4)
original.patch(2, Array(2), 0)      // Array[Int] = Array(0, 1, 2, 3, 4)
like image 74
The Archetypal Paul Avatar answered Dec 13 '22 06:12

The Archetypal Paul