使用类型为 Numeric[A] 的隐式参数似乎被忽略
Use of an implicit parameter of type Numeric[A] seems to be ignored
作为 Scala 的新手,我一直在玩 fold
、reduce
和 scan
。我想查看元素在函数参数上传递的顺序以及最终结果的组装方式。因为我打算在数字和字符串列表上使用它,所以我定义了以下带有类型参数的辅助函数:
scala> def vizAdd[A](p1:A, p2:A):A = {
| val res:A = p1 + p2
| println( s" * ($p1, $p2) => $res" )
| res
| }
<console>:8: error: type mismatch;
found : A
required: String
val res = p1 + p2
^
Post Addition with generic type parameter in Scala提出一个解决方案,重点是+方法应该需要数值类型才能操作,所以在方法中加入一个Numeric[A]类型的隐式参数应该做的伎俩。不幸的是:
scala> def vizAdd[A](p1:A, p2:A)(implicit n: Numeric[A]):A = {
| val res:A = p1 + p2
| println( s" * ($p1, $p2) => $res" )
| res
| }
<console>:8: error: type mismatch;
found : A
required: String
val res:A = p1 + p2
^
用 [A:Numeric]
代替 (implicit n: Numeric[A])
的语法也不起作用...
编译在提到的 post(下面的代码)中实现的单例对象“GenericTest”会导致相同的错误:“found: A, required: String”。
object GenericTest extends App {
def func1[A](x: A, y: A)(implicit n: Numeric[A]): A = x + y
}
我在这里错过了什么?
我正在使用 Scala 2.11.5
Numeric
trait有plus
、times
等方法,用法如下:
def func1[A](x: A, y: A)(implicit n: Numeric[A]): A = n.plus(x, y)
您正在寻找的是一个隐式转换,它丰富了 A
以具有像 +
、*
等中缀操作,即这个:
import scala.math.Numeric.Implicits.infixNumericOps
def func1[A](x: A, y: A)(implicit n: Numeric[A]): A = x + y
或更多的语法糖:
def func1[A: Numeric](x: A, y: A): A = x + y
作为 Scala 的新手,我一直在玩 fold
、reduce
和 scan
。我想查看元素在函数参数上传递的顺序以及最终结果的组装方式。因为我打算在数字和字符串列表上使用它,所以我定义了以下带有类型参数的辅助函数:
scala> def vizAdd[A](p1:A, p2:A):A = {
| val res:A = p1 + p2
| println( s" * ($p1, $p2) => $res" )
| res
| }
<console>:8: error: type mismatch;
found : A
required: String
val res = p1 + p2
^
Post Addition with generic type parameter in Scala提出一个解决方案,重点是+方法应该需要数值类型才能操作,所以在方法中加入一个Numeric[A]类型的隐式参数应该做的伎俩。不幸的是:
scala> def vizAdd[A](p1:A, p2:A)(implicit n: Numeric[A]):A = {
| val res:A = p1 + p2
| println( s" * ($p1, $p2) => $res" )
| res
| }
<console>:8: error: type mismatch;
found : A
required: String
val res:A = p1 + p2
^
用 [A:Numeric]
代替 (implicit n: Numeric[A])
的语法也不起作用...
编译在提到的 post(下面的代码)中实现的单例对象“GenericTest”会导致相同的错误:“found: A, required: String”。
object GenericTest extends App {
def func1[A](x: A, y: A)(implicit n: Numeric[A]): A = x + y
}
我在这里错过了什么?
我正在使用 Scala 2.11.5
Numeric
trait有plus
、times
等方法,用法如下:
def func1[A](x: A, y: A)(implicit n: Numeric[A]): A = n.plus(x, y)
您正在寻找的是一个隐式转换,它丰富了 A
以具有像 +
、*
等中缀操作,即这个:
import scala.math.Numeric.Implicits.infixNumericOps
def func1[A](x: A, y: A)(implicit n: Numeric[A]): A = x + y
或更多的语法糖:
def func1[A: Numeric](x: A, y: A): A = x + y