scalapattern-matchingunapply

Playing with Nat without case classes


I just create a definition in scala for Naturals, and also a PLUS operation:

abstract class Nat {

  def +(other:Nat):Nat = this match {
    case Zero => other
    case Succ(x) => x + Succ(other)
  }

}

object Zero extends Nat {
  override def toString = "Zero"
}

And for the definition of Succ, i tryit not to use a Case class, for learning purposes. My first approach was:

class Succ(x: Nat) extends Nat {
  override def toString = "Succ(" + x.toString + ")"
}

object Succ {
  def apply(x: Nat) = new Succ(x)

  def unapply(s: Succ) = Some(s.x)
}

But the compiler throws me an error

Error:(  , ) value x is not a member of Succ
  def unapply(s: Succ) = Some(s.x)
                              ^

I make an explicit method for get X, and it works

class Succ(x: Nat) extends Nat {

  def getX = x

  override def toString = "Succ(" + x.toString + ")"
}

object Succ {
  def apply(x: Nat) = new Succ(x)

  def unapply(s: Succ) = Some(s.getX)

}

Why?


Solution

  • Constructor arguments are only visible inside the class. If you want to make it a field, you'll have to say so:

    class Succ(val x: Nat) extends Nat { … }
    //         ^^^