Scala does not provide such flexibility in its matches (which may be good, because you need to know about errors that result from unintentional reuse of variables).
If you have a large number of identical elements, you can consider a nested match (but note that you will not exit the internal match, which will be completed later by the external match, so you will have to process everything locally):
list match { case x :: rest => rest match { case `x` :: `x` :: `x` :: xs => println("Four of the same") case _ => println("Well, nonempty at least") } case _ => println("Boring, there nothing here!") }
Pay attention to the return outputs, which mean "we already have this variable, check it, do not set it!".
Alternatively, if you have specialized functions that you reuse, you can create a custom connector:
object FourOf { def unapplySeq(xs: List[Int]): Option[(Int, List[Int])] = xs match { case x :: y :: z :: a :: rest if x==y && y==z && z==a => Some((x,rest)) case _ => None } }
and then use it whenever you need this complex template:
list match { case FourOf(x,rest) => println("four of the same") case x :: more => println("Nonempty") case _ => println("Yawn") }
None of them are as neat and flexible as you probably hoped, but again, I'm not sure that switching between assigning and testing the same variable in a matching statement is a good way to write clear code anyway.
source share