首页 > 解决方案 > 不能通过下限规则限制方法

问题描述

我已经开始阅读有关 scala 泛型的信息。谁能解释我为什么 whit 代码有效?

sealed abstract class Animal

class Cat extends Animal
class Dog extends Animal

class Box[A >: Animal] {
  def set(a: A): A = ???
}

val catBox: Box[Animal] = new Box[Animal]
val dog = new Dog
catBox.set(dog)

标签: scalagenericslower-bound

解决方案


我在这里猜测,您所说的“不起作用”的意思是您没想到能够进入您的set,因为不是.DogcatBoxDogAnimal

不过这是意料之中的。您对Box[Animal].set变得 的定义def set(a: Animal): Animal。现在, aDog 一个Animal,所以,它满足定义。

我不太明白你的意图是什么。绑定的类型Box限制了您可以创建的框类型:

 new Box[Animal] // compiles
 new Box[Dog]    // does not compile - Dog is not a superclass of Animal
 new Box[Any]    // compiles - Any is a superclass of everything 

但是你为什么要像这样限制它并没有多大意义。也许,您想要的是上限:

 class AnimalBox[A <: Animal]
 val animalBox = new AnimalBox[Animal] // compiles
 val dogBox = new AnimalBox[Dog] // compiles: Dog is a subclass of Animal
 val catBox = new AnimalBox[Cat] // compiles: Cat is a subclass of Animal
 val badBox = new AnimalBox[Any] // does not compile: Any is not a subclass

 animalBox.set(new Dog) // compiles: Dog is an Animal
 animalBox.set(new Cat) // compiles: Cat is an Animal
 animalBox.set(new Pear) // does not compile: Pear is not an Animal

 dogBox.set(new Dog) // compiles
 dogBox.set(new Cat) // does not compile: cat is not a dog

推荐阅读