【问题标题】:Playing with Nat without case classes在没有案例类的情况下与 Nat 一起玩
【发布时间】:2014-10-12 16:51:37
【问题描述】:

我只是在 scala 中为 Naturals 创建了一个定义,还有一个 PLUS 操作:

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"
}

对于 Succ 的定义,出于学习目的,我尽量不使用 Case 类。我的第一个方法是:

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)
}

但是编译器给我一个错误

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

我为获取 X 做了一个明确的方法,它可以工作

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)

}

为什么?

【问题讨论】:

    标签: scala pattern-matching unapply


    【解决方案1】:

    构造函数参数仅在类中可见。如果你想让它成为一个字段,你必须这样说:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-11
      • 1970-01-01
      • 2012-04-14
      • 2021-11-02
      • 2019-10-22
      • 1970-01-01
      • 2019-10-06
      • 2021-01-07
      相关资源
      最近更新 更多