简体   繁体   中英

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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM