类型成员和协方差

发布于 2024-10-22 11:49:58 字数 530 浏览 1 评论 0 原文

我猜想,“类型差异注释”(+-)不能应用于“类型成员”。为了向自己解释它,我考虑了以下 示例

abstract class Box {type T; val element: T}

现在,如果我想创建类 StringBox< /code> 我必须扩展 Box

class StringBox extends Box { type T = String; override val element = ""}

所以我可以说 Box自然是协变的>T。换句话说,具有类型成员的类在这些类型中是协变的。

有道理吗?
您如何描述类型成员和类型差异之间的关系?

I guess, "type variance annotations" (+ and -) cannot be applied to "type members". In order to explain it to myself I considered the following example

abstract class Box {type T; val element: T}

Now if I want to create class StringBox I have to extend Box:

class StringBox extends Box { type T = String; override val element = ""}

So I can say that Box is naturally covariant in type T. In other words, the classes with type members are covariant in those types.

Does it make sense ?
How would you describe the relationship between type members and type variance ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

幸福丶如此 2024-10-29 11:49:58

Box 的类型 T 是不变的,但这并不意味着没有什么可看的。

abstract class Box {
  type T
  def get: T
}
type InvariantBox = Box { type T = AnyRef }
type SortofCovariantBox = Box { type T <: AnyRef }

改变差异情况的是类型暴露的程度和完成的方式。抽象类型更加不透明。但你应该在 repl 中解决这些问题,这很有趣。

# get a nightly build, and you need -Ydependent-method-types
% scala29 -Ydependent-method-types

abstract class Box {
  type T
  def get: T
}
type InvariantBox = Box { type T = AnyRef }
type SortofCovariantBox = Box { type T <: AnyRef }

// what type is inferred for f? why?
def f(x1: SortofCovariantBox, x2: InvariantBox) = List(x1, x2)

// how about this?
def g[U](x1: Box { type T <: U}, x2: Box { type T >: U}) = List(x1.get, x2.get)

等等。

Box is invariant in its type T, but that doesn't mean there's nothing to see.

abstract class Box {
  type T
  def get: T
}
type InvariantBox = Box { type T = AnyRef }
type SortofCovariantBox = Box { type T <: AnyRef }

What alters the variance situation is the degree to which the type is exposed and the manner it is done. Abstract types are more opaque. But you should play with these issues in the repl, it's quite interesting.

# get a nightly build, and you need -Ydependent-method-types
% scala29 -Ydependent-method-types

abstract class Box {
  type T
  def get: T
}
type InvariantBox = Box { type T = AnyRef }
type SortofCovariantBox = Box { type T <: AnyRef }

// what type is inferred for f? why?
def f(x1: SortofCovariantBox, x2: InvariantBox) = List(x1, x2)

// how about this?
def g[U](x1: Box { type T <: U}, x2: Box { type T >: U}) = List(x1.get, x2.get)

And etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文