我有父母抽象类P
:
abstract class P {
def isEmpty: Boolean
}
然后我有2个子类Empty
和NonEmpty
:
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
定义为对象而不是类是有意义的。