scala - 不能通过下限规则限制方法
问题描述
我已经开始阅读有关 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
catBox
Dog
Animal
不过这是意料之中的。您对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
推荐阅读
- java - 如何在android studio中删除部分安装的sdk
- javascript - 如果您确实需要优化回流
- c++ - arma::Cube 的 row() 或 col() 成员似乎不起作用
- c# - 如何匹配新的 StackTrace 以抛出 Exception.StackTrace
- firebase - Flutter Firebase/Firestore 文档对 Future Builder 列表视图的参考
- php - 特定类别的木材/ TWIG spearate 模板
- angular - 如何在 Angular 6 中替换父组件上的子组件?
- dependency-injection - IdentityServer4 的自定义 UserRepository 依赖项未解决
- python - 如何从运行时代码访问 PyInstaller 挂钩文件命名空间中的变量?
- c++ - 使用 std::optional 传递 std::vector
通过引用到功能