【问题标题】:Can't restrict method by Lower-bound rule不能通过下限规则限制方法
【发布时间】:2018-12-28 13:05:43
【问题描述】:

我已经开始阅读有关 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)

【问题讨论】:

  • 它实际上工作得很好(除了???,这与泛型无关......或其他任何东西)。对于未来,在提出问题时,请尝试解释您正在寻求帮助的特定问题,只是“不起作用”太宽泛了。不要指望人们猜测,你的意思是什么。
  • 哦,是的,这是我的错。问题是为什么我可以调用方法 set(dog) 如果我通过下限限制类型 A - 动物。因为 Dog 是 Animal 的子类型,而不是超类型

标签: scala generics lower-bound


【解决方案1】:

我在这里猜测,您所说的“不起作用”是指您没想到能够将setDog 放入您的catBox,因为Dog 不是Animal

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

我不太明白你的意图是什么。 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

【讨论】:

    【解决方案2】:

    运算符??? 等价于throw new NotImplementedError

    因此,当您调用catBox.set(dog) 时,您将抛出异常。

    【讨论】:

      猜你喜欢
      • 2020-07-22
      • 1970-01-01
      • 1970-01-01
      • 2017-02-23
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      • 1970-01-01
      相关资源
      最近更新 更多