确保通用方法的参数在特征方法中具有相同的类型

我有一个密封的特征和一些扩展该特征的案例类,例如:

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 Foos

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)
}

但是我遇到两个问题:

  1. T needs to be present on Example as far as I can tell. Can I make method generic without "infecting" the rest of the trait?
  2. I'm not actually sure my type restriction gets the result I would like. Can anyone confirm if my intuition is correct?
评论
  • Lamb
    Lamb 回复

    You need to specify <:

    : stands for context bound and works in combination with a type class like trait Zoo[T]

    <: stands for upper type bound

    trait Example {
        def method[T <: Foo](arg1: T, arg2: T)
    }