2011-03-18 68 views
10

我想,「類型差異註釋」(+-)不能應用於「類型成員」。爲了解釋給我自己,我認爲以下example類型成員和協方差

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

現在,如果我想創建一流StringBox我不得不延長Box

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

所以我可以說,Box自然類型T協變。換句話說,類型成員的類在這些類型中是協變的。

它有道理嗎?
你會如何描述類型成員和類型差異之間的關係?

+0

可否請你改變公認的答案保羅的?礦井不夠。 – 2012-02-05 15:53:53

+0

@ DanielC.Sobral完成。謝謝 – Michael 2012-02-06 09:02:47

回答

14

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)