2016-07-14 39 views
0

我想将一个函数应用于列表中的所有对象,其中列表中的所有对象都从一个公共类继承。在这个函数中,我想使用一个implicit类来确保根据对象的类型应用正确的操作。通过ClassTag将隐式泛型参数应用于列表

例如,我想确保使用下面的employeeConverter转换列表中的所有Employee对象。调用convertEmployee直接工作就好了,但将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应用到列表中?

+0

如果你使用更正式的'println(List(Employee(2)).map(e => convert(e))'''它有什么区别吗? –

+0

他们的打印是无关紧要的 - 它是'List(Employee(2)map convert',无法编译。打印只是为了说明结果。 –

+0

Bob是对的,编译器根本找不到隐式参数您正在使用的语法。 – nkconnor

回答

2

编译器在这种情况下需要一点点的手持。这工作:

println(List(Employee(2)) map { e => convert(e) })