I have a parent abstract class P:
abstract class P {
def isEmpty: Boolean
}
Then I have 2 subclasses Empty and NonEmpty:
class Empty extends P {
def isEmpty: Boolean = true
}
In NonEmpty, I need to define a function union as follows:
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)
}
}
}
However, I got an error as:
14: error: value name is not a member of NonEmpty
case n: NonEmpty => println("NonEmpty:" + n.name)
^
How come?
Simply make name a public (i.e. visible) value member of the class.
class NonEmpty(val name: String) extends P { ...
Or you could turn it into a case class. With that the parameter is made public automatically and the pattern matching a little more clean and concise.
case NonEmpty(n) => print("NonEmpty:" + n)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With