类型成员和协方差 [英] Type Members and Covariance

查看:86
本文介绍了类型成员和协方差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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}

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

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

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

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

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 ?

推荐答案

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

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)

等等。

这篇关于类型成员和协方差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆