I want to create a type class that will constrain its defined abstract type to have a 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
also has to be upper-bound to some Z
, but it seems to make no difference.
Is there a way to express ClassTag
constraint on B
?
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.
Make it an abstract def
instead, and let the concrete implementation of A
provide it:
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.