Match a tuple of unknown size in scala
pattern-matching, scala, tuples
Solution
Tuples are structures for heterogeneous types. As such, they implement the `productIterator` trait, so you could do:
v.productIterator.toList match {
case "Dr" :: _ => "What's up, Doc?"
case "Mr" :: name :: _ => s"Welcome, Mr. ${name}"
case _ => "Have we met?"
}
But your example really looks like you want a `Seq[String]` straight away. Is there any reason for wishing to use tuples?
Problem
Is there way to partially match a `tuple` without having to specify the size? For example, if I had a tuple ``` val v = ( "Dr", "John","H", "Watson") ``` I'd like to be able to do something like : ``` v match { case ( "Dr", : _*) => "What's up, Doc?" case ( "Mr", name, :_*) => s"Welcome, Mr. ${name}" case _ => "Have we met?" } ``` This doesn't compile, `:_*` normally means an undetermined number of parameters, but can't be used in this case apparently. The idea would be to be able to use this matcher for any tuple bigger than 2. I know i can do it converting `v` to a `List` (for example) first, just want to know if it's possible to do it with a `tuple`. EDIT: the most information I found on the web is this discussion, which dates back to scala 2.8, so I'm gonna with the 'No, you can't' answer.