无法在伴随 class 中找到隐式参数

Could not find implicit parameter in companion class

我有一个像这样的 Number Wrapper

class NumWrapper[A<:AnyVal](var v: A)(implicit n:Numeric[A]) {
  def +(other: A): NumWrapper[A] = {
    new NumWrapper(n.plus(v, other))
  }

  def -(other: A): NumWrapper[A] = {
    new NumWrapper(n.minus(v, other))
  }
}

一切正常。但是当我想进行隐式转换时,我创建了一个伴侣 class 如下:

object NumWrapper {
  implicit def toNumWrapper[A<:AnyVal](v: A) = new NumWrapper[A](v)
}

但是编译时出现错误:

could not find implicit value for parameter n: Numeric[A]

这里有什么问题吗?为什么它在编译时试图找到类型 A 的隐式匹配?

非常感谢您的帮助。

根据您的代码,

class NumWrapper[A<:AnyVal](var v: A)(implicit n:Numeric[A])

调用new NumWrapper[MyType](v)一个Numeric[MyType]必须在隐式解析的范围内。

所以当你有

object NumWrapper {
  implicit def toNumWrapper[A<:AnyVal](v: A) = new NumWrapper[A](v)
}

正在调用此 NumWrapper 构造函数,Numeric[A] 必须解析。事实并非如此,编译器会引发上述错误。

Scala 中的隐式检查是在编译时执行的(它是一种静态类型语言)。如果编译器无法识别在调用位置可用的单个、明确、匹配的隐式值,它会抱怨。

您可以在此处解决此问题的一种方法是将隐式要求添加到 toNumWrapper 方法中:

object NumWrapper {
  implicit def toNumWrapper[A<:AnyVal](v: A)(implicit n:Numeric[A]) = new NumWrapper[A](v)
}

这将隐式数字的要求推到需要隐式转换的位置,例如,在控制台中,我可以这样写:

scala> val chk1 = 3L
chk1: Long = 3

scala> val chk2 = NumWrapper.toNumWrapper(chk1)
chk2: NumWrapper[Long] = NumWrapper@1e89017a

编译器很高兴,因为(我认为 - 不完全确定)Long 值带有它自己的隐式 Numeric[Long]。