我有两个案例类 Person 和 Employee

case class Person(identifier: String) {}

case class Employee (salary: Long) extends Person {}

我收到以下错误:
Unspecified value parameters: identifier: String
Error: case class Employee has case ancestor Person, but case-to-case inheritance is prohibited. To overcome this limitation, use extractors to pattern match on non-leaf nodes

我是 Scala 的新手,无法理解我必须做什么。

版本:
斯卡拉:2.11

最佳答案

不幸的是,我担心案例类不可能扩展另一个案例类。

“普通”类中的继承如下所示:

class Person(val identifier: String) {}

class Employee(override val identifier: String, salary: Long)
  extends Person(identifier) {}

val el = new Employee("abc-test", 999)
println(el.identifier) // => "abc-test"

如果你想用 case 类实现类似的效果,你需要联系 trait s:
trait Identifiable {
  def identifier: String
}

case class Person(identifier: String) extends Identifiable {}

case class Employee(identifier: String, salary: Long)
  extends Identifiable {}

val el = Employee("abc-test", 999)
println(el.identifier) // => "abc-test"

定义提取器

Extractor 提供了一种定义模式匹配中使用的匹配语句的方法。它在 object 方法中的 unaply 中定义。

让我们再次考虑第一个示例,添加对提取器的支持:
class Person(val identifier: String)

class Employee(override val identifier: String, val salary: Long)
  extends Person(identifier)

object Person {
  def unapply(identifier: String): Option[Person] = {
    if (identifier.startsWith("PER-")) {
      Some(new Person(identifier))
    }
    else {
      None
    }
  }
}

object Employee {
  def unapply(identifier: String): Option[Employee] = {
    if (identifier.startsWith("EMP-")) {
      Some(new Employee(identifier, 999))
    }
    else {
      None
    }
  }
}

现在,让我们定义一个使用这些提取器定义模式匹配的方法:
def process(anInput: String): Unit = {
  anInput match {
    case Employee(anEmployee) => println(s"Employee identified ${anEmployee.identifier}, $$${anEmployee.salary}")
    case Person(aPerson) => println(s"Person identified ${aPerson.identifier}")
    case _ => println("Was unable to identify anyone...")
  }
}

process("PER-123-test") // => Person identified PER-123-test
process("EMP-321-test") // => Employee identified EMP-321-test, $999
process("Foo-Bar-Test") // => Was unable to identify anyone...

关于scala - 从另一个案例类扩展案例类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53986931/

10-15 20:14