How to say that a type parameter must have one supertype of alternative supertypes?

We can say that a parameter of type T must have a certain supertype S_1:

class Test[T <: S_1] 

Is there a way to say that a type parameter must have at least one supertype of several supertype alternatives? Something like (pseudo-code):

 class Test[T <: S_1 || S_2] 

Or: Is this impossible, because such a design does not make sense and will be a hint of a design error in the code?

+6
source share
2 answers

Short answer:. An intuitive solution is to make S_1 and S_2 common attribute that represents the set of capabilities that are required for your parameter of type T Use this trait as the upper bound for T

Additional features:

  • If S_1 and S_2 not related to each other in nature, and your requirement for type T is that it has certain elements (which are implemented by both S_1 and S_2 ), you can use the structural type to formulate this (concept behind is called duck typing ).

  • If for some reason you really need T be a subclass of S_1 or S_2 , and you cannot change these types, you can use implicits to convert both of them to the newly introduced internal type S_1_or_2 , which can then be used as the upper bound for T .

+9
source

Let me deploy Niklas a second alternative. Implicit parameters can be used to prove something like that, so this seems to be what you need. It will look like this:

 class ThingIWantToProve[T] object ThingIWantToProve { // Here I define the proofs I need implicit def s1IsProvable: ThingIWantToProve[S_1] = new ThingIWantToProve[S_1] implicit def s2IsProvable: ThingIWantToProve[S_2] = new ThingIWantToProve[S_2] } class Test[T : ThingIWantToProve] // here I use a context bound 
+3
source

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


All Articles