Scala匹配子类与参数

  • 本文关键字:参数 子类 Scala scala
  • 更新时间 :
  • 英文 :


我有父母抽象类P

abstract class P {
  def isEmpty: Boolean
}

然后我有2个子类EmptyNonEmpty

class Empty extends P {
  def isEmpty: Boolean = true
}

NonEmpty中,我需要定义一个函数union如下:

class NonEmpty(name: String) extends P {
  def isEmpty: Boolean = false
  def union(that: P): Unit = {
    that match {
      case e: Empty => print("empty")
      case n: NonEmpty => print("NonEmpty:" + n.name)
    }
  }
}

但是,我有一个错误,例如:

14: error: value name is not a member of NonEmpty
     case n: NonEmpty => println("NonEmpty:" + n.name)
                                                 ^

怎么来?

只需使name公共(即可见)的值成员。

class NonEmpty(val name: String) extends P { ...

或者您可以将其变成case class。随着该参数是自动公开的,模式匹配一些更干净和简洁。

case NonEmpty(n) => print("NonEmpty:" + n)

name是类构造函数的参数,但尚未为NonEmpty类的对象分配该字段。

替换
class NonEmpty(name: String) extends P

class NonEmpty(val name: String) extends P

这样做定义一个字段并分配了构造函数中传递的值。

看来您正在使用这些类来建模像数据结构之类的树。在这种情况下,将Empty定义为对象而不是类是有意义的。

最新更新