在普通 Scala 中,以下断言通过
assert(1D > 0F)
assert(1F > 0)
assert(1L > 0)
assert(1 > 0.toShort)
assert(1.toShort > 0.toChar)
然而 ScalaTest 中类似的匹配器fail https://github.com/scalatest/scalatest/issues/349
1D shouldBe > (0F)
1F shouldBe > (0)
1L shouldBe > (0)
1 shouldBe > (0.toShort)
1.toShort shouldBe > (0.toChar)
解决方法是使两侧的类型相同,例如
1D shouldBe > (0D)
为什么它在 Scala 中有效,但在 Scalatest 中无效,或者它的签名是什么?> https://github.com/scalatest/scalatest/blob/9e127207941836b19490c6cfacf9087e2c8ece89/scalatest/src/main/scala/org/scalatest/Matchers.scala#L2753
def >[T : Ordering] (right: T): ResultOfGreaterThanComparison[T]
这使它失败?
Vanilla Scala 的工作原理是自动类型转换,即0F
被投射到0D
这是许多语言中的常见做法。
更有趣的问题是为什么shouldBe
不起作用。去除隐式收益的糖分
new AnyShouldWrapper[Double](leftSideValue = 1D,
pos = ???,
prettifier = ???)
.shouldBe(new ResultOfGreaterThanComparison[Double](right = 0D))
new AnyShouldWrapper[Double](leftSideValue = 1D,
pos = ???,
prettifier = ???)
.shouldBe(new ResultOfGreaterThanComparison[Float](right = 0F))
这会导致超载的实现shouldBe
。前一个案例是这样的here https://github.com/scalatest/scalatest/blob/release-3.0.5/scalatest/src/main/scala/org/scalatest/Matchers.scala#L6899和后者here https://github.com/scalatest/scalatest/blob/release-3.0.5/scalatest/src/main/scala/org/scalatest/Matchers.scala#L6860.
看了源码,似乎只有一个原因1D shouldBe > (0F)
实际上编译是支持数组比较shouldBe
关键词。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)