参数类型+函数需要一个字符串作为第二个参数? [英] Parametric type + function requires a string as second parameter?

查看:46
本文介绍了参数类型+函数需要一个字符串作为第二个参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class TestClass[T](val x: T) {def +(other: TestClass[T]) = x + other.x}

这个定义给了我以下编译错误:

this definition gives me the following compile error:

错误:类型不匹配;
发现:T
必需:字符串
def +(other: TestClass[T]) = x + other.x

error: type mismatch;
found : T
required: String
def +(other: TestClass[T]) = x + other.x

在 Scala 中不能使用 Int 或 Double 作为类型参数并使用加法吗??

is it not possible to use Int or Double as a type parameter and use addition in Scala??

推荐答案

首先,错误信息具有误导性.scalac 尝试在值 x 上找到方法 +.这在 T 类型上不存在,它可以是任何类型.这称为无界类型参数.所以它试图应用和隐式视图.Predef.any2stringadd 符合要求.

Firstly, the error message is misleading. scalac tries to find a method + on value x. This doesn't exist on type T, which could be any type whatsoever. This is called an unbounded type parameter. So it tries to apply and implicit view. Predef.any2stringadd fits the bill.

您可以禁用此隐式转换,并查看真正的错误:

You can disable this implicit conversion, and see the real error:

 ~/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 中,泛型方法必须在其定义时进行类型检查,仅基于抽象类型的边界.

In C++, the type checking is done after the type parameter is provided, at each call site. So this style of code would work. In Scala, the generic method must be type checked at its definition, based on only on the bounds of the abstract types.

根据 VonC 的建议,您可能希望在类型参数 T 上提供上下文绑定,以将 if 约​​束为具有 Numeric 特征的相应实例的类型.

As suggested by VonC, you might want to provide a context bound on the type parameter T to constrain if to a type that has a corresponding instance of the Numeric trait.

class TestClass[T: Numeric](val x: T) { 
  def +(other: TestClass[T]): T = {
    val num = implicitly[Numeric[T]]
    import num._
    x + other.x
  }
}

以下是所有显式隐式的外观:

Here's how this looks with all the implicits made explicit:

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

这篇关于参数类型+函数需要一个字符串作为第二个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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