Scala 编译器无法识别视图边界 [英] Scala compiler not recognizing a view bound

查看:48
本文介绍了Scala 编译器无法识别视图边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过这行代码

def **[A <% Numeric[A]](l:List[A],m:List[A])=l.zip(m).map({t=>t._1*t._2})

但是在编译时,我收到此错误

However on compilation, I get this error

error: value * is not a member of type parameter A
def **[A <% Numeric[A]](l:List[A],m:List[A])=l.zip(m).map({t=>t._1*t._2})

当我查看 Numeric trait 的源代码时,我看到定义了一个 * 操作.

When I look at the source for the Numeric trait, I see a * op defined.

我做错了什么?

推荐答案

Numeric 的实例本身并不是一个数字,而是一个提供算术运算的对象.例如,Numeric[Int] 类型的对象 num 可以像这样将两个整数相加: num.plus(3, 5) 结果此操作的整数 7.

The instance of Numeric is not a number itself, but it is an object that offers operations to do the arithmetic. For example, an object num of type Numeric[Int] can add two integers like this: num.plus(3, 5) The result of this operation is the integer 7.

对于整数来说,这是非常微不足道的.但是,对于所有基本数字类型,都有一个 隐式 Numeric 实例可用.如果您定义自己的数字类型,则可以提供一种.

For integers, this is very trivial. However, for all basic numerical types, there is one implicit instance of Numeric available. And if you define your own numeric types, you can provide one.

因此,您应该让 A 的边界保持打开状态,并添加一个类型为 Numeric[A] 的隐式参数,用它来进行计算.像这样:

Therefore, you should leave the bounds for A open and add an implicit parameter of type Numeric[A], with which you do the calculations. Like this:

def **[A](l:List[A],m:List[A])(implicit num:Numeric[A])=l.zip(m).map({t=>num.times(t._1, t._2)})

当然,num.times(a,b) 看起来不如 a*b 优雅.在大多数情况下,人们可以接受这一点.但是,您可以将值 a 包装在支持运算符的 Ops 类型的对象中,如下所示:

Of course, num.times(a,b) looks less elegant than a*b. In most of the cases, one can live with that. However, you can wrap the value a in an object of type Ops that supports operators, like this:

// given are: num:Numeric[A], a:A and b:A
val a_ops = num.mkNumericOps(a)
val product = a_ops * b

由于方法 mkNumericOps 被声明为 implicit,您也可以导入它并隐式使用它:

Since the method mkNumericOps is declared implicit, you can also import it and use it implicitly:

// given are: num:Numeric[A], a:A and b:A
import num._
val product = a * b

这篇关于Scala 编译器无法识别视图边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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