在 scala 抽象类中,如果你想定义一个上下文绑定,你可以简单地使用,例如 [T: ClassTag] 在参数中,但是这在 trait 中是不可能的:
trait Foo[T: ClassTag]
Error:(11, 35) traits cannot have type parameters with context bounds `: ...' nor view bounds `<% ...'
trait Foo[T: ClassTag]
^
如果你定义:
trait Foo[T] {
implicit def ctg: ClassTag[T] = implicitly[ClassTag[T]]
}
object Bar extends Foo[Int]
那么任何在 Bar 中读取 ctg 的尝试都会触发 StackOverflowError,因为隐式参数变为尾递归。
那么,让 ctg 在自动将子类公开到上下文绑定的特征中定义的最佳方法是什么?