Pattern match question

Hi, take this example:

case class A(a: String)
object A {
	def unapply(s: String): Option[A] = {

case class B(a: String)
object B {
	def unapply(s: String): Option[B] = {

def testA(args: List[String]) = {
	args match {
		case A(a) :: B(b) :: "other" :: Nil =>

Is it possible to have a and b refactored to a separate class AB:

case class AB(a: A, b: B)

So that one can have this pattern-matching?

def testAB(args: List[String]) = {
	args match {
		case AB((a, b)) :: "other" :: Nil =>

And have a and b be of the correct type (A and B)?


when you decompose A and B both will be of type String correct?

to have the compiler refer to them as A and B (instead of String) I think you need Opaque Type Aliases as documented here: Opaque Types | Scala 3 — Book | Scala Documentation

In my first example testA the decomposed types are of type a: A and b: B, so in testAB I want the types to be the same, of type A and B respectively, same result as in testA.

closest I could get, issue being the decomposed els are of type AB, and not A, B respectively, and I used a single Trait instead of a single class

trait AB[T]:
def unapply(s: T): Option[T] = Option(s)

case class A(s: String) extends AB[String]
case class B(s: String) extends AB[String]

object AB:
def test[T](args: List[AB[T]]) = args match
case A(a) :: B(b) :: _ => (A(a), B(b))
case _ => (args(0), args(1))

val (first, second) = AB.test(List(A(“ima a”), B(“ima b”)))
//val first: AB[String] = A(ima a)
//val second: AB[String] = B(ima b)

Short answer, AFAIK, no.

Simply because such an extractor would need to consume two elements of the List instead of one, which would contradict what the :: extractor does.

So, rather, you would need something like like ABTail that could be used like this:

args match {
  case ABTail(a, b, "other" :: Nil) =>

But, to be honest, what is the use case for that over the original code?

PS: If this is just for argument parsing, you would rather want to look at the excellent libraries we have for that.

That’s a good tip, thanks!
My use-case is a partial-function which among other things takes a list of Strings where the first parts of the string are structurally equivalent but should decompose to different values, of different types.

Okey then yeah in that case you need an extractor that picks the whole list.