给定参数化方法的以下签名
def double[A <: Byte](in:List[A]): List[A] = {
//double the values of the list using foldLeft
//for ex. something like:
in.foldLeft(List[A]())((r,c) => (2*c) :: r).reverse
//but it doesn't work! so..
}
在处理参数化类型的foldLeft 之前,我试图获得以下内容
def plainDouble[Int](in:List[Int]): List[Int] = {
in.foldLeft(List[Int]())((r:List[Int], c:Int) => {
var k = 2*c
println("r is ["+r+"], c is ["+c+"]")
//want to prepend to list r
// k :: r
r
})
}
但是,这会导致以下错误:
$scala fold_ex.scala
error: overloaded method value * with alternatives:
(x: Double)Double <and>
(x: Float)Float <and>
(x: Long)Long <and>
(x: scala.Int)scala.Int <and>
(x: Char)scala.Int <and>
(x: Short)scala.Int <and>
(x: Byte)scala.Int
cannot be applied to (Int(in method plainDouble))
val k = 2*c
^
one error found
如果我将def的签名更改为以下内容:
def plainDouble(in:List[Int]): List[Int] = { ...}
工作和输出:
val in = List(1,2,3,4,5)
println("in "+ in + " plainDouble ["+plainDouble(in)+"]")
是
in List(1, 2, 3, 4, 5) plainDouble [List(2, 4, 6, 8, 10)]
如果我遗漏了一些显而易见的东西,我深表歉意。
问题是一种名称隐藏:
def plainDouble[Int](in:List[Int]): List[Int] = {
^^^
// this is a type parameter called "Int"
您正在声明一个名为Int
的类型变量,同时还试图使用具体类型Int
,这会导致混淆。例如,如果删除类型变量(因为它实际上没有使用)或将其重命名为I
,则代码将编译。
@DNA是正确的,因为plainDouble[Int]
声明了一个名为Int
的类型参数,与实际类型无关。因此,你试图使其非通用实际上仍然是通用的,但在某种程度上并不明显。
但是最初的问题呢?
scala> def double[A <: Byte](in: List[A]): List[A] = in.foldLeft(List.empty[A])((r,c) => (2*c) :: r)
<console>:15: error: type mismatch;
found : x$1.type (with underlying type Int)
required: A
def double[A <: Byte](in: List[A]): List[A] = in.foldLeft(List.empty[A])((r,c) => (2*c) :: r).reverse
^
这里的问题是2 * c
是Int
,而不是A
。Int
上的*(byte: Byte)
方法返回另一个Int
。因此产生消息CCD_ 12。请注意,如果您强制转换为A
,它将编译:
def double[A <: Byte](in: List[A]): List[A] =
in.foldLeft(List.empty[A])((r,c) => (2*c).toByte.asInstanceOf[A] :: r).reverse
请注意,在转换为A
之前,我还必须调用toByte
。这并不是泛型工作的一个光辉例子,但关键是不兼容的返回类型导致了错误。
还要注意,如果删除2 *
:,它不会发生
def double[A <: Byte](in: List[A]): List[A] =
in.foldLeft(List.empty[A])((r,c) => c :: r).reverse
编辑:
您可以考虑将Numeric
特性用于此类泛型。
import scala.math.Numeric.Implicits._
def double[A: Numeric](in: List[A])(implicit i2a: Int => A): List[A] =
in.map(_ * 2)
这依赖于一个隐式Numeric[A]
可用于您的数字类型(scala.math.Numeric
对象中有一个,用于您想要的几乎任何数字类型)。它还依赖于从Int
到A
的隐式转换,因此我们可以编写a * 2
。我们可以通过使用+
来放弃这个约束:
def double[A: Numeric](in: List[A]): List[A] = in.map(a => a + a)