ps0604
ps0604

Reputation: 1071

Matching arrays in Scala

In this example code I need to print each Seq, problem is that when I match it I only have one variable x instead of an array. How to get the array? Moreover, this code only prints do nothing twice.

   var seq = Seq(Seq(1,2,3),Seq(4,5,6))
   seq.foreach { seq2 =>
     seq2 match {
       case Seq(x) => println(x)
       case _ => println("do nothing")
     }
   }

Upvotes: 0

Views: 90

Answers (1)

Andrey Tyukin
Andrey Tyukin

Reputation: 44918

If you have a homogeneous Seq[Seq[Int]], you don't have to match at all:

var seq = Seq(Seq(1,2,3),Seq(4,5,6))
seq foreach println

If you have a sequence of mixed elements like this:

var seq = Seq[Any](Seq(1,2,3), 42)

then you can match by type Seq, which is equivalent to an isInstanceOf. In this case, you will have to add a _ for the erased type of Seq:

seq.foreach { seq2 =>
  seq2 match {
    case s: Seq[_] => println(s)
    case _ => println("do nothing")
  }
}

You should avoid the second variant. It would be preferable to create a custom sealed trait with case classes and do the pattern matching properly:

sealed trait ValidSeqContent
case class IntInSeq(i: Int) extends ValidSeqContent
case class SeqOfIntsInSeq(seq: Seq[Int]) extends ValidSeqContent

val seq: Seq[ValidSeqContent] = Seq(
  SeqOfIntsInSeq(Seq(1,2,3)),
  IntInSeq(42)
)

Then you can do pattern matching without isInstanceOf-like matches:

seq.foreach{ x =>
  x match {
    case SeqOfIntsInSeq(s) => println(s)
    case _ => { /* do nothing */ }
  }
}

Upvotes: 2

Related Questions