Implementing a class for pattern matching

For instance,

val list = List(1,2,3) list match { case a :: b => case _ => } 

you can match the head and tail of the list with :: or ParseResult tokens with ~ . What to do to create a class that can be mapped like previous classes?

UPD:

And there is an opportunity to write:

 case class @ ... List(1,2,3,4) match { case 1 @ 2 @ 3 @ 4 => } 
+4
source share
2 answers

There are not many. These two statements are equivalent:

 case x :: xs => case ::(x, xs) => 

Say you want something to split the list into odds and evens, and name it ** . You can write an extractor as follows:

 object ** { def unapply(xs: List[Int]) = Some(xs partition (_ % 2 == 0)) } scala> List(1,2,3) match { | case evens ** odds => println("Evens: "+evens+"\nOdds: "+odds) | } Evens: List(2) Odds: List(1, 3) 
+8
source

If you define your class as the case class , it can be matched this way.

If you want to map a template to something other than a class constructor, you can use extractors to define custom templates.

+3
source

Source: https://habr.com/ru/post/1310787/


All Articles