我如何接受在 Scala 中扩展 class 的泛型

How do I accept a generic that extends a class in Scala

我有类似以下内容...

class Base {
  def doSomething = {...}
}

class B extends Base{
  val text = "foo"
  ...
}
class C extends Base{
  val value = "bar"
}

我想要一种接受任何 class 扩展 Base 但保留其扩展属性的方法。我试过这个...

def myMethod[A extends Base](obj: A): Unit{
  ...
}

但这没有用。我如何创建允许这样做的方法?

您正在寻找的概念是类型上限。子类型关系的 standard notation<:。这种精确的表示法也用在 Scala 语法中来表达类型界限:

// upper type bound, `A` must be subtype of `U`,
// analogous to Java's "A extends U"
def foo[A <: U]: Unit = ???

// lower type bound, `A` must be supertype of `L`,
// analogous to Java's "A super L"
def bar[A >: L]: Unit = ???

// Both upper and lower bounds simultaneously:
def baz[A >: U <: L]: Unit = ???

在您的情况下,A 应该是 Base 的子类型,即它应该受上面的 Base 限制:A <: Base

def myMethod[A <: Base](obj: A): Unit{
  ...
}

来自 Java 时要牢记的另一个重要区别是,在 Scala 中,您既有使用位置差异的可能性,也有声明位置差异的可能性。