突变会像打破协方差一样破坏违反性吗?

发布于 2025-01-17 19:57:13 字数 515 浏览 2 评论 0原文

变异的协变容器是不健全的。

例如,在不使用任何特定语言的情况下,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文