参数类型 +函数需要字符串作为第二个参数?
-
30-09-2019 - |
题
class TestClass[T](val x: T) { def +(other: TestClass[T]) = x + other.x }
该定义给我以下编译错误:
错误:键入不匹配;
找到:t
必需:字符串
def +(其他:testClass [t])= x + other.x
是否不可能将int或double用作类型参数并在scala中使用添加?
解决方案
首先,错误消息具有误导性。 Scalac试图找到一种方法 +
价值 x
. 。这在类型上不存在 T
, ,这可能是任何类型。这称为无界类型参数。因此,它试图应用和隐性视图。 Predef.any2stringadd
适合法案。
您可以禁用此隐式转换,并查看真正的错误:
~/code/scratch: cat plus.scala
import Predef.{any2stringadd => _, _}
class TestClass[T](val x: T) {
def +(other: TestClass[T]) = x + other.x
}
~/code/scratch: scalac plus.scala
plus.scala:4: error: value + is not a member of type parameter T
def +(other: TestClass[T]) = x + other.x
^
one error found
在C ++中,在每个呼叫站点提供了类型参数之后进行类型检查。因此,这种代码风格将起作用。在Scala中,必须仅基于抽象类型的范围,在其定义上检查通用方法。
正如VONC所建议的那样,您可能需要在类型参数上提供上下文 T
约束是否具有具有相应实例的类型 Numeric
特征。
class TestClass[T: Numeric](val x: T) {
def +(other: TestClass[T]): T = {
val num = implicitly[Numeric[T]]
import num._
x + other.x
}
}
这是所有隐含的显式的外观:
class TestClass[T]{
implicit <paramaccessor> private[this] val evidence$1: Numeric[T] = _;
def this(x: T)(implicit evidence$1: Numeric[T]): TestClass[T] = {
TestClass.super.this();
()
};
def +(other: TestClass[T]): T = {
val num: Numeric[T] = scala.Predef.implicitly[Numeric[T]](TestClass.this.evidence$1);
import num._;
num.mkNumericOps(TestClass.this.x).+(other.x)
}
}
不隶属于 StackOverflow