2011-02-23 39 views
2

如何和为什么“VAL”和“案例”影响类型系统? (尤其是方差)逆变和Val

Welcome to Scala version 2.8.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_22). 
Type in expressions to have them evaluated. 
Type :help for more information. 

scala> class E[-A] 
defined class E 

scala> class F[-A](val f: E[A] => Unit) 
<console>:6: error: contravariant type A occurs in covariant position in type => (E[A]) => Unit of value f 
class F[-A](val f: E[A] => Unit) 
        ^ 
scala> case class C[-A](f: E[A] => Unit) 
<console>:6: error: contravariant type A occurs in covariant position in type => (E[A]) => Unit of value f 
    case class C[-A](f: E[A] => Unit) 

scala> class F[-A](f: E[A] => Unit)  
defined class F 

回答

4

考虑一下:

trait Equal[-A] { def eq(a1: A, a2: A): Boolean } 
val e = new Equal[Option[Int]] { 
    def eq(a1: Option[Int], a2: Option[Int]) = a1 forall (x => a2 forall (x ==)) 
} 

// Because Equal is contra-variant, Equal[AnyRef] is a subtype of Equal[String] 
// Because T => R is contra-variant in T, Equal[AnyRef] => Unit is a supertype 
// of Equal[String] => Unit 
// So the follow assignment is valid 
val f: Equal[AnyRef] => Unit = (e1: Equal[String]) => println(e1.eq("abc", "def")) 


// f(e) doesn't compile because of contra-variance 
// as Equal[Option[Int]] is not a subtype of Equal[AnyRef] 

// Now let's tell Scala we know what we are doing 
class F[-A](val f: Equal[A @uncheckedVariance] => Unit) 

// And then let's prove we are not: 
// Because F is contra-variant, F[Option[Int]] is a subtype of F[AnyRef] 
val g: F[Option[Int]] = new F(f) 

// And since g.f is Equal[Option[Int]] => Unit, we can pass e to it. 
g.f(e) // compiles, throws exception 

如果f是不可见的外F,也不会发生这个问题。

+0

所以这意味着我的例子中的决定因素是'val'和'case'为构造函数参数生成公共成员? – ladrl 2011-02-24 07:46:14

+0

从打字的角度来看,你可以认为你的代码是“E类[-A] {def f:A = ...},这使得A处于协变位置。” – 2011-02-24 17:25:56

+0

@ladrl这是正确的。 – 2011-02-24 17:58:55

3

你问的是什么差异?如果你知道什么是差异,这是不言自明的。没有“val”或“c​​ase”的示例没有涉及A的外部可见成员,因此它不会引起方差错误。

+0

保罗,这是一个扯淡的答案:如果你不是*你*,这将是一个downvote! – 2011-02-23 23:51:39

+0

答案故意指出这个问题。 – extempore 2011-02-24 00:45:34

1

在“VAL”表示该字段是外部可见的。考虑:

val f: E[Any] => Unit = { ... } 
val broken: F[Int] = new F[Any](f) // allowed by -A annotation 
val f2: E[Int] => Unit = broken.f // must work (types match) 
val f3: E[Int] => Unit = f // type error 

基本上,我们设法不安全地施放了f而没有明确地采取行动。这仅适用于f是可见的,即,如果将其定义为val或使用案例类。

0

这里有一个逆变 “输出通道”,它只是打印到控制台:

class OutputChannel[-T] { 
    def write(t:T) = println(t); 
} 

这是在行动:

val out:OutputChannel[Any] = new OutputChannel[Any] 
out.write(5) 

没有什么有趣呢。关于逆变很酷的事情是,你可以现在这个输出通道安全地分配到一个接受的T任何子类:

val out2:OutputChannel[String] = out 
out2.write("five") 
out2.write(55) //wont compile 

现在,想象一下,如果我们增加了一个历史跟踪到输出通道 - 回馈的列表迄今为止发出的东西。

//!!! as you've seen code like this won't compile w/ contravariant types!!!! 
class OutputChannel[-T] { 
    var history:List[T] = Nil 
    def write(t:T) = { 
    history = history :+ t; 
    println(t); 
    } 
} 

如果上述没有进行编译时,基于字符串的输出信道的用户将有一个问题:由于逆变允许此类型的“变窄”(即,从任何给字符串这里

//history(0) is an Int - runtime exception (if scala allowed it to compile) 
val firstStringOutputted:String = out2.history(0) 

),类型系统不能暴露类型T的值,例如我所做的这个“history”字段,或者你所拥有的“f”字段。

其他著名的“逆向”的功能和比较器:

val strHashCode:String => Int = { s:Any => s.hashCode } //function which works with any object 
val strComp:Comparator<String> = new HashCodeComparator() //comparator object which works with any object