如何模式匹配继承树中的抽象父类 [英] How to pattern match abstract parent classes in a inheritance tree

查看:61
本文介绍了如何模式匹配继承树中的抽象父类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是具有 Java 背景的 Scala 新手.

I am new to scala with a java background.

有没有办法在类继承树中模式匹配超类(或特征),叶子作为案例类,节点抽象类或特征?据我所知,case类继承是不允许的.

Is there a way to pattern match super classes (or traits) in a class inheritance tree with leafs as case classes and nodes abstract classes or traits? As far as I know case class inheritance is not allowed.

我认为在大型继承树中模式匹配抽象类会很有帮助

I think that pattern matching abstract classes in large inheritance tree would be very helpful

在下面的代码中,最后一种情况是在编译过程中匹配语句错误

In the following code the last case in the match statement errors during compilation

sealed trait Person {
   def name: String
}

case class Customer(name: String, email: String) extends Person

sealed trait Employee extends Person {
   def id: Int
}

case class Worker(name: String, id: Int, skills: Array[String]) extends Employee

case class Manager(name: String, id: Int, title: String) extends Employee

def process(p: Person) = p match {
   case Customer(_, email) => email
   case Employee(name, _) => name + "@acme.com"
}

推荐答案

您缺少 Employee 中的 name 字段和 unapply 方法在 Employee 的伴随对象中:

You were missing the name field in Employee and an unapply method in the companion object of Employee:

sealed trait Employee extends Person {
  def id: Int
  def name: String
}

object Employee {
  def unapply(e: Employee): Option[(String, Int)] =
    Option(e) map { e =>
      (e.name, e.id)
    }
}

通过上述更改,处理方法没有问题:

With the above changes the process method gives no problems:

def process(p: Person) = p match {
  case Customer(_, email) => email
  case Employee(name, _) => name + "@acme.com"
}

这篇关于如何模式匹配继承树中的抽象父类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆