首页 > 解决方案 > 抽象类中未定义类型时出现类型不匹配错误

问题描述

我是 Scala 的新手,遇到了下面代码中的编译器错误。我正在尝试实现一个表示 +ve 整数的自然数类。我在定义应该遵循的 + 运算符时遇到问题,def + (that: Nat): Nat但我没有在抽象类中定义它,我得到以下错误。但是一旦在抽象类中定义它就会消失。

[error] D:\Scala\NatuarlNum\src\main\scala\NatuarlNum.scala:31:46: type mismatch;
[error]  found   : Nat
[error]  required: String
[error]   def + (that: Nat): Nat = new Succ(previous.+(that))

我无法理解为什么它说 required 是“String”而不是“Nat”。即使函数声明出现在定义之前。

这是代码:

abstract class Nat {
  def isZero: Boolean
  def predecessor: Nat
  def successor: Nat
  //def + (that: Nat): Nat  // By uncommentng this line the error will go away
  //def - (that: Nat): Nat
  override def toString: String = {
    if (this.isZero) {
      "0"
    } else {
      "{" + this.predecessor.toString + "}"
    }
  }
}

object Zero extends Nat {
  def isZero = true
  def predecessor = throw new Error("0.predecessor")
  def successor: Nat = new Succ(this)
  def + (that: Nat): Nat = that
}

class Succ(previous: Nat) extends Nat {
  def isZero = false
  def predecessor = previous
  def successor: Nat = new Succ(this)
  def + (that: Nat): Nat = new Succ(previous.+(that))  // The error is from this line
}

object NatuarlNum {
  def main(args: Array[String]): Unit = {
    val zero = Zero
    val one = new Succ(zero)
    val two = new Succ(one)
    val three = new Succ(new Succ(new Succ(Zero)))

    println("0 = " + zero)
    println("1 = " + one)
    println("2 = " + two)
    println("3 = " + three)

    println("0 + 2 = " + (zero + two))
    println("2 + 2 = " + (two + two))   

  }
}

如果没有 + 运算符,我的代码将编译并给出如下结果:

0 = 0
1 = {0}
2 = {{0}}
3 = {{{0}}}
0 + 2 = {{0}}

标签: scala

解决方案


好吧,您在代码中回答了您的问题。

  //def + (that: Nat): Nat  // By uncommentng this line the error will go away
  //def - (that: Nat): Nat

问题是,

def + (that: Nat): Nat = new Succ(previous.+(that))

previous是 type Nat,它没有+运算符覆盖。

如果您取消注释运算符的定义Nat- 它将起作用。

+operator的默认实现将String作为参数,它解释了您收到的错误消息,请参阅any2stringadd了解更多信息,并且有一张可以删除隐式+运算符定义。

来自编译器警告:

Predef 已弃用(自 2.13.0 起):隐式注入 + 已弃用。转换为字符串以调用 +


推荐阅读