breezymri
breezymri

Reputation: 4343

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?

Upvotes: 3

Views: 471

Answers (2)

shaktimaan
shaktimaan

Reputation: 12092

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.

Upvotes: 2

jwvh
jwvh

Reputation: 51271

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)

Upvotes: 5

Related Questions