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

scala – 参数类型函数需要一个字符串作为第二个参数?

发布时间:2020-12-16 09:09:45 所属栏目:安全 来源:网络整理
导读:class TestClass[T](val x: T) { def +(other: TestClass[T]) = x + other.x } 这个定义给了我以下编译错误: 错误:类型不匹配; 发现:T 必需:字符串 def(其他:TestClass [T])= x other.x 是不是可以使用Int或Double作为类型参数并在Scala中使用添加? 解

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型上不存在,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中,在每个呼叫站点提供type参数后进行类型检查.所以这种代码风格可行.在Scala中,泛型方法必须在其定义时进行类型检查,仅基于抽象类型的边界.

正如VonC所建议的那样,您可能希望在类型参数T上提供上下文绑定,以约束是否具有相应数字特征实例的类型.

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

(编辑:李大同)

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

    推荐文章
      热点阅读