作为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
^
在Scala中使用泛型类型参数的Post Addition提出了一个解决方案,重点是+方法应该需要一个数字类型来操作,所以在方法中添加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])
的语法也不起作用。。。
按照上面提到的帖子(下面的代码)中实现的方式编译singleton对象"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
特性有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