Search code examples
scalaunapply

understanding unapply without case class


I am trying out below example to understand unapply,

class Emp(name: String, age: Int)

object Emp {
  def apply(name: String, age: Int): Emp = new Emp(name, age)

  def unapply(emp: Emp): Option[(String, Int)] = Some(emp.name, emp.age)
}

Unfortunately, it fails with compilation error Cannot resolve symbol name, Cannot resolve symbol age.

Whereas, when i declare Emp as case class, it works prefectly fine without any compilation error.

Can someone please explain reason behind this?

Note: scalaVersion- 2.12.7


Solution

  • the error tell you, that scala can't see the properties in class Emp. in order to expose them, you need smth like this (more on this in here):

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

    moreover, Some accepts only one argument, so you need to return a pair:

    Some((emp.name, emp.age))