加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 为什么隐式搜索会受到不相关的类型参数的影响?

发布时间:2020-12-16 18:29:33 所属栏目:安全 来源:网络整理
导读:考虑 Scala中某些测量功能单元的简化片段: object UnitsEx { case class Quantity[M : MInt,T: Numeric](value: T) { private val num = implicitly[Numeric[T]] def *[M2 : MInt](m: Quantity[M2,T]) = Quantity[M,T](num.times(value,m.value)) } implici
考虑 Scala中某些测量功能单元的简化片段:

object UnitsEx {
  case class Quantity[M <: MInt,T: Numeric](value: T) {
    private val num = implicitly[Numeric[T]]
    def *[M2 <: MInt](m: Quantity[M2,T]) = 
      Quantity[M,T](num.times(value,m.value))
  }

  implicit def measure[T: Numeric](v: T): Quantity[_0,T] = Quantity[_0,T](v)
  implicit def numericToQuantity[T: Numeric](v: T): QuantityConstructor[T] = 
    new QuantityConstructor[T](v)

  class QuantityConstructor[T: Numeric](v: T) {
    def m = Quantity[_1,T](v)
  }

  sealed trait MInt
  final class _0 extends MInt
  final class _1 extends MInt
}

此代码段显示了我目前使用的用法和编译器错误:

import UnitsEx._

(1 m) * 1 // Works
1 * (1 m) // Doesn't work:
/*
<console>:1: error: overloaded method value * with alternatives:
(x: Double)Double <and>
(x: Float)Float <and>
(x: Long)Long <and>
(x: Int)Int <and>
(x: Char)Int <and>
(x: Short)Int <and>
(x: Byte)Int
cannot be applied to (UnitsEx.Quantity[UnitsEx._1,Int])
1 * (1 m)
^
*/

用度量包装1将解决问题,但为什么不应用隐含的范围?

如果我删除下一个片段中的类型参数M,它就会开始工作,虽然我看不到该类型参数与隐式搜索的关系:

object UnitsEx2 {   
  case class Quantity[T: Numeric](value: T) {
    private val num = implicitly[Numeric[T]]
    def *(m: Quantity[T]) = Quantity[T](num.times(value,m.value))
  }

  implicit def measure[T: Numeric](v: T): Quantity[T] = Quantity[T](v)
  implicit def numericToQuantity[T: Numeric](v: T): QuantityConstructor[T] = 
    new QuantityConstructor[T](v)

  class QuantityConstructor[T: Numeric](v: T) {
    def m = Quantity[T](v)
  }
}

这是预期的还是类型检查器的已知限制?

解决方法

如果您将*运算符重命名为例如mult则1 mult(1 m)适用于两种情况. 这并没有回答你的问题,但暗示可能会对严重超载的*运算符产生一些干扰.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读