I have a sealed trait and some case classes that extend that trait, like so:
sealed trait Foo
case class Bar extends Foo
case class Baz extends Foo
In a different part of my code, I have a trait with a method on it that operates on Foo
s
trait Example {
def method(arg1: Foo, arg2: Foo)
}
However, I would really like to ensure that arg1
and arg2
always have the same type; that is, they should both be either Bar
or Baz
, and never a mix. My first intuition is to use generics:
trait Example {
def method[T: Foo](arg1: T, arg2: T)
}
But I run into two problems:
T
needs to be present onExample
as far as I can tell. Can I makemethod
generic without "infecting" the rest of the trait?- I'm not actually sure my type restriction gets the result I would like. Can anyone confirm if my intuition is correct?