简体   繁体   中英

Scala match subclass with parameter

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 (ie 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)

name is the argument for the constructor of the class but the field hasn't been assigned that value for the objects of NonEmpty class.

Replace
class NonEmpty(name: String) extends P
with
class NonEmpty(val name: String) extends P

Doing this defines a field and assigns the value passed in the constructor.

It seems that you are using these classes to model a tree like data structure. In that case, it would make sense to define Empty as an object instead of a class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM