【问题标题】:Comparison matchers fail on mixed numeric types比较匹配器在混合数字类型上失败
【发布时间】:2019-10-28 13:55:39
【问题描述】:

在原版 Scala 中,以下断言通过

assert(1D > 0F)
assert(1F > 0)
assert(1L > 0)
assert(1 > 0.toShort)
assert(1.toShort > 0.toChar)

然而 ScalaTest 中的类似匹配器 fail

1D shouldBe > (0F)
1F shouldBe > (0)
1L shouldBe > (0)
1 shouldBe > (0.toShort)
1.toShort shouldBe > (0.toChar)

一种解决方法是让两边的类型相同,例如

1D shouldBe > (0D)

为什么它在 Scala 中有效,但在 Scalatest 中无效,或者> 的签名是什么原因

def >[T : Ordering] (right: T): ResultOfGreaterThanComparison[T]

这让它失败了?

【问题讨论】:

  • 有趣的是,1D should be > 0D 有效,而 1D should be > 0F 不编译

标签: scala scalatest matcher comparison-operators


【解决方案1】:

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,后一种情况是here

查看源代码后,似乎1D shouldBe > (0F)实际编译的唯一原因是支持与shouldBe关键字进行数组比较。

【讨论】:

    猜你喜欢
    • 2015-10-11
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多