【问题标题】:Specs implicit conversion conflicts with Scala PredefSpecs 隐式转换与 Scala Predef 冲突
【发布时间】:2012-02-21 10:44:20
【问题描述】:

我的代码中有一个类型别名,如下所示:

type Time = Double

而且我经常在测试和应用程序中将 Long 值传递给使用这种类型的函数。例如:

 def at(time : Time) : T = {
     // Do Something
 }

 at(System.currentTimeMillis)

除非在我得到以下错误的测试中运行,否则此代码可以正常工作:

  found   : Long
  required: com.github.oetzi.echo.Echo.Time
  Note that implicit conversions are not applicable because they are ambiguous:
  both method long2double in object Predef of type (x: Long)Double
  and method longToDouble in trait NumericBaseMatchers of type (s: Long)Double
  are possible conversion functions from Long to com.github.oetzi.echo.Echo.Time

在查找 NumericBaseMatchers 之后,它似乎是 Specs 测试框架的一部分(我的测试是在 Specs 1 中编写的)。我尝试运行代码以在解释器中获取错误,并且在测试之外很好。

有什么方法可以消除歧义,以便将 Long 值传递给 Double/Time 函数?为什么 Specs 尝试创建自己的 LongToDouble 转换,而 Scala 已经提供了这种转换?

【问题讨论】:

    标签: scala testing types implicit-conversion specs


    【解决方案1】:

    如果您想停用继承的隐式转换,您可以这样做:

      override def longToDouble(s: Long) = super.longToDouble(s)
    

    为方便起见,如果您将其添加到新特性中,您可以在需要时将特性混合到您的规范中:

      trait NoConversion {
        override def longToDouble(s: Long) = super.longToDouble(s)
      }
    
      class MySpecification extends NoConversion {
         ...
      }
    

    【讨论】:

      【解决方案2】:

      尝试取消导入其中一个。

      import NumericBaseMatchers.{longToDouble => _}
      

      【讨论】:

      • 这似乎不起作用。 NumericBaseMatchers 是一个特征。导入抱怨没有伴生对象?
      猜你喜欢
      • 2016-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-15
      • 1970-01-01
      • 2016-03-24
      • 2012-04-15
      • 2018-09-16
      相关资源
      最近更新 更多