我正在使用 scala 语言来定义 2 个运算符::++
并且++:
作为彼此的精确镜像: a :++ b == b ++: a
,它们显然不是可交换的: a :++ b != a ++: b
。
这是我用于测试的 scala 代码:
import org.scalatest.FunSpec
import scala.collection.immutable.ListMap
case class Example(self: ListMap[String, String] = ListMap.empty) {
def :++(v: Example) = this.copy(
self ++ (v.self -- self.keys.toSeq)
)
def ++:(v: Example) = {
println("forward: " + :++(v))
println("reverse: " + (v :++ this))
v :++ this
}
}
class OperatorOverrideSuite extends FunSpec {
val p1 = Example(ListMap("a" -> "1"))
val p2 = Example(ListMap("a" -> "2"))
it(":++ operator should preserve first value") {
assert(p1 :++ p2 == p1)
}
it("++: operator should preserve second value") {
assert(p1 ++: p2 == p2)
}
}
第一个测试看起来一切都很好,但是在运行时出现以下错误:
forward: Example(Map(a -> 2))
reverse: Example(Map(a -> 1))
Example(Map(a -> 1)) did not equal Example(Map(a -> 2))
ScalaTestFailureLocation: com.schedule1.datapassports.params.OperatorOverrideSuite$$anonfun$2 at (OperatorOverrideSuite.scala:30)
Expected :Example(Map(a -> 2))
Actual :Example(Map(a -> 1))
<Click to see difference>
org.scalatest.exceptions.TestFailedException: Example(Map(a -> 1)) did not equal Example(Map(a -> 2))
at org.scalatest.Assertions$class.newAssertionFailedException(Assertions.scala:528)
at org.scalatest.FunSpec.newAssertionFailedException(FunSpec.scala:1630)
at org.scalatest.Assertions$AssertionsHelper.macroAssert(Assertions.scala:501)
at ...
从打印的消息看来,scala 覆盖了我的运算符并自行反转操作数,是什么可能导致 scala 编译器以这种方式运行?它是一个错误吗?
我正在使用最新的 scala 2.11 和最新的 Java 8u181 进行测试。