通过ClassTag将隐式通用参数应用于列表

时间:2016-07-14 21:54:14

标签: list scala types implicit

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

例如,我想确保使用下面的Employee转换列表中的所有employeeConverter个对象。使用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应用于列表?

1 个答案:

答案 0 :(得分:2)

在这种情况下,编译器需要一点点手持。这有效:

println(List(Employee(2)) map { e => convert(e) })
相关问题