比较匹配器在混合数字类型上失败 [英] Comparison matchers fail on mixed numeric types

查看:44
本文介绍了比较匹配器在混合数字类型上失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 vanilla Scala 中,以下断言通过

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)

然而 ScalaTest 中的相似匹配器失败

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)

为什么它在 Scala 中有效,而在 Scalatest 中无效,或者 >

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]

这让它失败了吗?

推荐答案

Vanilla Scala 工作由于自动类型转换,即 0F 被强制转换为 0D 这是一个常见的做法多种语言.

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

更有趣的问题是为什么 shouldBe 不起作用.去除隐含物的糖分

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

导致 shouldBe 的重载实现.前一种情况 此处 和后者这里.

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

看了源码,好像唯一的原因1D shouldBe >(0F) 实际编译是为了支持数组比较,加上shouldBe关键字.

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.

这篇关于比较匹配器在混合数字类型上失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆