Scala 游览

上限类型界限

语言

在 Scala 中,类型参数抽象类型成员可能受类型界限的约束。此类类型界限限制了类型变量的具体值,并可能揭示有关此类类型成员的更多信息。上限类型界限 T <: A声明类型变量T引用类型A的子类型。以下示例演示了类PetContainer的类型参数的上限类型界限

abstract class Animal {
 def name: String
}

abstract class Pet extends Animal {}

class Cat extends Pet {
  override def name: String = "Cat"
}

class Dog extends Pet {
  override def name: String = "Dog"
}

class Lion extends Animal {
  override def name: String = "Lion"
}

class PetContainer[P <: Pet](p: P) {
  def pet: P = p
}

val dogContainer = new PetContainer[Dog](new Dog)
val catContainer = new PetContainer[Cat](new Cat)
abstract class Animal:
  def name: String

abstract class Pet extends Animal

class Cat extends Pet:
  override def name: String = "Cat"

class Dog extends Pet:
  override def name: String = "Dog"

class Lion extends Animal:
  override def name: String = "Lion"

class PetContainer[P <: Pet](p: P):
  def pet: P = p

val dogContainer = PetContainer[Dog](Dog())
val catContainer = PetContainer[Cat](Cat())
// this would not compile
val lionContainer = new PetContainer[Lion](new Lion)
// this would not compile
val lionContainer = PetContainer[Lion](Lion())

class PetContainer采用类型参数P,该参数必须是Pet的子类型。DogCatPet的子类型,因此我们可以创建一个新的PetContainer[Dog]PetContainer[Cat]。但是,如果我们尝试创建一个PetContainer[Lion],我们会收到以下错误

类型参数 [Lion] 不符合类 PetContainer 的类型参数界限 [P <: Pet]

这是因为Lion不是Pet的子类型。

此页面的贡献者