Can I restrict a generic type argument to one of two unrelated classes?

I would like to do something like this (actually doesn't work):

class A[T <: B | C] 

... and expect this to be valid:

 new A[B] new A[C] 

... and this will result in a compiler error:

 new A[D] 

Is this possible?

+5
source share
1 answer

You can use implicits:

 trait AArg[T] class A[T](implicit e: AArg[T]) implicit val argB = new AArg[B] { } implicit val argC = new AArg[C] { } 

although this does not prevent anyone from creating an implicit val of type AArg[D] .

+4
source

Source: https://habr.com/ru/post/1204473/


All Articles