Incerteza
Incerteza

Reputation: 34924

Set the "double" restriction for a generic parameter

I have 3 classes:

abstract class Abs1 { ... }
abstract class Abs2 { ... }

class MyClass[T <: /*Abs1 or Abs2*/] { ... }

Is there any way specify that T must be a child of Abs1 or Abs2?

Upvotes: 1

Views: 54

Answers (1)

Samuel Tardieu
Samuel Tardieu

Reputation: 2081

In short: no.

What would that mean for an object of type T? What method would you be able to call, since you do not know whether it has any methods exposed in Abs1 (since it might be a type derived from Abs2) or any methods exposed in Abs2 (since it might be a type derived from Abs1). You could only used methods defined for Any, or any other common parent of Abs1 and Abs2 if they have some.

In this case, you might as well accept this super type directly, and manipulate Any (or a common parent type of Abs1 and Abs2) objects in your methods rather than objects of type T. Or you could not put any constraint on T: that would give you a generic class that you can instantiate with any specific type, but you would not know anything about this type either except that it derives from Any.

Upvotes: 2

Related Questions