[英]ClassTag for type class parameter
I want to create a type class that will constrain its defined abstract type to have a ClassTag
. 我想创建一个类型类,将其定义的抽象类型约束为ClassTag
。 Here is a simplified example: 这是一个简化的例子:
trait A[T] {
type B <: Z
val tag = implicitly[ClassTag[B]]
}
// Error:(8, 24) No ClassTag available for A.this.B
// val tag = implicitly[ClassTag[B]]
^
I need B
to have a ClassTag[B]
and I can't define A
like trait A[T, B: ClassTag]
because I want A
be implicitly available for T
, like in def foo[T: A](t: T)
. 我需要B
有一个ClassTag[B]
,我不能定义A
像trait A[T, B: ClassTag]
因为我希望A
可以隐含地用于T
,就像在def foo[T: A](t: T)
。 B
also has to be upper-bound to some Z
, but it seems to make no difference. B
也必须上限到一些Z
,但它似乎没有区别。
Is there a way to express ClassTag
constraint on B
? 有没有办法在B
上表达ClassTag
约束?
There is no way for the compiler to provide you with a ClassTag
here, as it has no clue what B
might end up being. 编译器没有办法在这里为你提供ClassTag
,因为它不知道B
最终会是什么。
Make it an abstract def
instead, and let the concrete implementation of A
provide it: 使它成为一个抽象的def
,让A
的具体实现提供它:
trait A[T] {
type B <: Z
def tag: ClassTag[B] // you may want to declare it as implicit
}
and, for instance, 例如,
new A[Int] {
type B = Z
def tag = implicitly
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.