通过ClassTag将隐式通用参数应用于列表 [英] Applying implicit generic parameters to a list via ClassTag
问题描述
我想将一个函数应用于列表中的所有对象,其中列表中的所有对象都继承自一个公共类.在此函数中,我想使用implicit
类来确保根据对象的类型应用正确的操作.
I would like to apply a function to all objects in a list, where all objects in the list inherit from a common class. In this function, I would like to use an implicit
class to ensure that the correct operation is applied based on the object's type.
例如,我想确保使用以下employeeConverter
转换列表中的所有Employee
对象.直接使用Employee
调用convert
很好,但是将convert
应用于Employee
对象的列表是编译器错误.
For example, I want to ensure that all Employee
objects in a list are converted using the employeeConverter
below. Calling convert
with the Employee
directly works just fine, but applying convert
to a list of Employee
objects is a compiler error.
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
}
}
上面的代码正确打印了以下内容:
The above code correctly prints the following:
$ scalac Example.scala && scala Example
(Employee(1),Employee(1))
但是,如果我取消注释COMPILER ERROR
所示的行,则会出现此编译器错误:
However, if I uncomment the line indicated with COMPILER ERROR
, I get this compiler error:
Example.scala:20: error: could not find implicit value for parameter converter: Example.Converter[T]
println(l map convert)
^
这是可以使用ClassTag
解决的问题吗?如何修改此示例以将convert
应用于列表?
Is this a problem that can be resolved using ClassTag
? How can I modify this example to apply convert
to a list?
推荐答案
在这种情况下,编译器需要一些手动操作.这有效:
The compiler needs a little bit of hand-holding in this case. This works:
println(List(Employee(2)) map { e => convert(e) })
这篇关于通过ClassTag将隐式通用参数应用于列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!