scala - 抽象类中未定义类型时出现类型不匹配错误
问题描述
我是 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}}
解决方案
好吧,您在代码中回答了您的问题。
//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 起):隐式注入 + 已弃用。转换为字符串以调用 +
推荐阅读
- magento - 如何在 minicart magento 2 中显示总计代替小计
- swift - Swift - 由于 statusBarWindows 导致应用程序崩溃
- solace - 安慰监控:寻找普罗米修斯出口商
- git - 交互式变基 git
- c# - 如何使用 Elastic 低级客户端批量插入嵌套类型对象?
- php - 在 PHP 搜索结果中循环 XPATH
- javascript - 使用反应测试库检查文本是否出现在元素内
- c# - Specflow 未在 Visual Studio 2019 中执行测试
- json - 使用 JQ 替换 JSON 模板中的变量
- swift - UINavigationController 在推送视图的左侧添加自动填充