0
我想将一个函数应用于列表中的所有对象,其中列表中的所有对象都从一个公共类继承。在这个函数中,我想使用一个implicit
类来确保根据对象的类型应用正确的操作。通过ClassTag将隐式泛型参数应用于列表
例如,我想确保使用下面的employeeConverter
转换列表中的所有Employee
对象。调用convert
与Employee
直接工作就好了,但将convert
应用于Employee
对象列表是一个编译器错误。
import scala.reflect.ClassTag
object Example {
abstract class Person { def age: Int }
case class Employee(age: Int) extends Person
class Converter[T] { def convert(t: T) = (t,t) }
def convert[T <: Person:ClassTag](p: T)(implicit converter: Converter[T]) =
converter.convert(p)
def main(args: Array[String]): Unit = {
implicit val employeeConverter = new Converter[Employee]()
println(convert(Employee(1)))
//println(List(Employee(2)) map convert) // COMPILER ERROR
}
}
上面的代码正确打印如下:
$ scalac Example.scala && scala Example
(Employee(1),Employee(1))
但是,如果我取消与COMPILER ERROR
指示的路线,我得到这个编译器错误:
Example.scala:20: error: could not find implicit value for parameter converter: Example.Converter[T]
println(l map convert)
^
这是一个问题那可以使用ClassTag
解决?我如何修改这个例子来将convert
应用到列表中?
如果你使用更正式的'println(List(Employee(2)).map(e => convert(e))'''它有什么区别吗? –
他们的打印是无关紧要的 - 它是'List(Employee(2)map convert',无法编译。打印只是为了说明结果。 –
Bob是对的,编译器根本找不到隐式参数您正在使用的语法。 – nkconnor