Is it possible to have a generic method with an type bound that amounts to "every possible concrete subclass of this trait, but not the trait itself?"
As an example, suppose I have the following inheritance hierarchy:
sealed trait Fruit
case class Apple() extends Fruit
case class Orange() extends Fruit
...
case class Watermelon() extends Fruit
I want to define a method def eatFruit[T <: ???](fruit: Seq[T])
that will allow T
to be of type Apple
, Orange
, Watermelon
, etc. but not of type Fruit
. The type bound [T <: Fruit]
obviously doesn't do the job.
The original impetus for this is that we have a FruitRepository
class that allows batched/bulk inserts of different fruits. The batching is done externally to the class, so at the moment it has a lot of methods along the lines of saveApples(apples: Seq[Apple])
, saveOranges(oranges: Seq[Orange])
, etc. that contain a lot of duplicate logic involving the creation of a batch update statement. I'd like to manage this in a more generic way, but any method saveFruit(fruit: Seq[Fruit])
would allow for e.g. a list containing both apples and oranges, which the repository can't handle.
...I'll also admit that I'm now generally curious as to whether this sort of type bound is possible, even if we end up solving the repository problem in a different way.