Comparison matchers fail on mixed numeric types

大兔子大兔子 提交于 2019-12-11 02:12:17

问题


In vanilla Scala the following assertions pass

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

however similar matchers in ScalaTest fail

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

A workaround is to make both sides the same type, for example

1D shouldBe > (0D)

Why does it work in Scala, but not in Scalatest, or what is it about the signature of >

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

that makes it fail?


回答1:


Vanilla Scala works due to automatic type conversion i.e. 0F is cast to 0D which is a common practise in many languages.

More interesting question is why shouldBe does not work. De-sugaring the implicits yields

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))

which leads to overloaded implementations of shouldBe. The former case goes here and the latter here.

After looking at the source code, it seems that the only reason 1D shouldBe > (0F) actually compiles is to support array comparison with shouldBe keyword.



来源:https://stackoverflow.com/questions/56589516/comparison-matchers-fail-on-mixed-numeric-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!