在 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
的子类型。Dog
和Cat
是Pet
的子类型,因此我们可以创建一个新的PetContainer[Dog]
和PetContainer[Cat]
。但是,如果我们尝试创建一个PetContainer[Lion]
,我们会收到以下错误
类型参数 [Lion] 不符合类 PetContainer 的类型参数界限 [P <: Pet]
这是因为Lion
不是Pet
的子类型。