突变会像打破协方差一样破坏违反性吗?
变异的协变容器是不健全的。
例如,在不使用任何特定语言的情况下,
interface Pet;
class Cat extends Pet { meow(); }
class Dog extends Pet { woof(); }
class Box[T] {
value: T;
}
var dog: Box[Dog] = new Box(new Dog);
var pet: Box[Pet] = dog;
pet.value = new Cat;
dog.woof(); // uh oh!
反变体类型是否存在类似的不合理性?
我的直觉是不会。粗略地说,上述不合理之处来自于这样一个事实:Box[T]
“包含”对 T
的引用,但是像 Predicate[T] 这样的逆变类型
根本不“包含”任何东西。
但是,我在这个主题上找不到太多内容。
Mutative covariant containers are unsound.
For example, and using no language in particular,
interface Pet;
class Cat extends Pet { meow(); }
class Dog extends Pet { woof(); }
class Box[T] {
value: T;
}
var dog: Box[Dog] = new Box(new Dog);
var pet: Box[Pet] = dog;
pet.value = new Cat;
dog.woof(); // uh oh!
Is there an analogous unsoundness with contravariant types?
My intuition is no. Loosely, the above unsoundness comes from the fact that a Box[T]
"contains" a reference to a T
, but a contravariant type like Predicate[T]
does not "contain" anything at all.
However, I can't find much on the subjet.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论