pattern matching - Scala - extractor unapply confusion -


i'm attempting write extractor(s) use in matching against multiple parameter case class. simplified example:

case class x(p1: string, p2: int) 

i'd each extractor objects define fixed value p1, , p2 defined on use. (a,b, etc cannot case class , subclass x, , use x(,) case) example apply method:

object {   def apply(p2: int): x = x("a", p2) }  object b {   def apply(p2: int): x = x("b", p2) }  ... 

for pattern matching, them match this:

x("a", 2) match {   case a(2) => true // <- should match: p1="a" , p2=2   case a(_) => true // <- should match: p1="a" , p2=_   case x("a", _) => true // <- should match: p1="a" , p2=_   case a(1) => false // <- should not match   case b(2) => false // <- should not match: p1="b" , p2=2 } 

i know need define unapply method in a, b, etc., i'm thoroughly confused signature , logic should be:

object {   def unapply(x: ???): option[???] = {     ???   }  } 

assistance, please?

unapply takes , returns option of whatever want extract. in case be:

scala> case class x(p1: string, p2: int) defined class x  scala> object {      |   def unapply(target: any): option[int] =      |     partialfunction.condopt(target) {      |       case x("a", p2) => p2      |     }      | } defined module  scala> val a(x) = x("a", 1) x: int = 1  scala> val a(x) = x("b", 1) scala.matcherror: x(b,1) (of class x) ... 

but honest, example came rewritten without a , b:

x("a",2) match {   case x("a", 2) => true   case x("a", 1) => false   case x("a", _) => true   case x("b", 2) => false } 

Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c# - Copy ObservableCollection to another ObservableCollection -

All overlapping substrings matching a java regex -