4

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

mukesh210
  • 2,792
  • 2
  • 19
  • 41

1 Answers1

5

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))
  • Right... need to declare it with `val` to expose it outside class. – mukesh210 Dec 10 '18 at 17:18
  • 1
    @Mukeshprajapati Scala classes behave like Java classes, in that they require getters and setters in order to access their parameters. Declaring them as `val` seems to bypass this, as does declaring the class as a `case class`. – James Whiteley Dec 11 '18 at 10:31