xyz
xyz

Reputation: 413

Using pattern matching to swap two elements in scala

I would like to use the pattern matching to swap the first two elements of an array, my code as shown below:

>scala val arr = Array(1,2,3,4,5)

>arr match { case Array(a,b,rest @ _*) => Array(b,a,rest)
// Array(2,1,Vector(3,4,5))

However, the result should be Array(2,1,3,4,5). How to revise it?

Upvotes: 0

Views: 344

Answers (1)

flavian
flavian

Reputation: 28511

Your problem is not passing in rest as a varargs, which is done using rest: _* syntax. This tells the compiler to pass in the collection methods as varargs, it works with Seq.

val arr = Array(1, 2, 3, 4, 5)
arr match { case Array(a, b, rest @ _*) => Array(b, a +: rest: _*) }

There's an Array.apply method than takes a first element followed by a varargs, but there's none to pass in two elements and then varargs. Because of that, we need to prepend the second element to the Seq before passing the whole thing as varargs.

That's why we end up with a +: rest: _*. +: are invoked on the right hand side of the expression, so the method +: is defined on Seq, by convention Scala methods that end with : are right associative.

Upvotes: 2

Related Questions