Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala match subclass with parameter

Tags:

scala

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?

like image 909
breezymri Avatar asked Dec 20 '25 00:12

breezymri


1 Answers

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)
like image 176
jwvh Avatar answered Dec 21 '25 16:12

jwvh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!