Why doesn't the example compile, aka how does (co-, contra-, and in-) variance work?

后端 未结 4 608
执笔经年
执笔经年 2021-01-21 16:43

Following on from this question, can someone explain the following in Scala:

class Slot[+T] (var some: T) { 
   //  DOES NOT COMPILE 
   //  \"COVARIANT paramete         


        
4条回答
  •  旧巷少年郎
    2021-01-21 17:28

    See Scala by example, page 57+ for a full discussion of this.

    If I'm understanding your comment correctly, you need to reread the passage starting at the bottom of page 56 (basically, what I think you are asking for isn't type-safe without run time checks, which scala doesn't do, so you're out of luck). Translating their example to use your construct:

    val x = new Slot[String]("test") // Make a slot
    val y: Slot[Any] = x             // Ok, 'cause String is a subtype of Any
    y.set(new Rational(1, 2))        // Works, but now x.get() will blow up 
    

    If you feel I'm not understanding your question (a distinct possibility), try adding more explanation / context to the problem description and I'll try again.

    In response to your edit: Immutable slots are a whole different situation...* smile * I hope the example above helped.

提交回复
热议问题