soupybionics soupybionics - 2 months ago 7
Scala Question

Understanding breakdown of case classes

If I have case class defined as below

case class Calculator(brand: String, model: String)


How does it's companion object's unapply method would look like? What type of arguments would it take?

I am not able to emulate this by defining a class and then it's companion object by myself.

class abc (age:Int, name:String) {
}

object abc {
def apply(age:Int, name:String) = new abc(age, name)
def unapply(obj:abc) = Some("test")
}

abc(1, "aaaa")
res6: abc = abc@269f4bad

res6 match {
| case abc(1, "aaaa") => println("found")
| }

error: too many patterns for object abc offering String: expected 1, found 2
case abc(1, "aaaa") => println("found")
^
<console>:14: error: type mismatch;
found : Int(1)
required: String
case abc(1, "aaaa") => println("found")

Answer

Tzach beat me to it..

Your error message btw. is because of the mismatch between the Option your unapply returns (which contains a single string) and the match in your case statement (with wants to match against a pair).

You could include a null check just to make sure (the compiler does, for case class companion objects):

class Abc(val age: Int, val name: String)

object Abc {
  def unapply(obj: Abc): Option[(Int, String)] = 
    if (obj == null)
      None
    else
      Some((obj.age, obj.name))
}

Shameless self-promotion: If you're interested in more details of pattern matching, you might find my little presentation "Everything you always wanted to know about pattern matching" useful.