我是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))
我不明白为什么它说必填项是“ 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}}
答案 0 :(得分:3)
好吧,您在代码中回答了问题。
//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
的类型为Nat
,没有+
运算符替代。
如果您取消注释Nat
中的运算符定义,它将起作用。
+
运算符的默认实现采用String
作为参数,它解释了您收到的错误消息,有关更多信息,请参见any2stringadd,并且有一个ticket删除隐式+
运算符定义。
来自编译器警告:
不建议使用Predef(从2.13.0开始):不建议使用+的隐式注入。转换为字符串以调用+