Comparison matchers fail on mixed numeric types

2019-07-09 03:20发布

问题:

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.