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

后端 未结 4 585
执笔经年
执笔经年 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:22

    @Daniel has explained it very well. But to explain it in short, if it was allowed:

      class Slot[+T](var some: T) {
        def get: T = some   
      }
    
      val slot: Slot[Dog] = new Slot[Dog](new Dog)   
      val slot2: Slot[Animal] = slot  //because of co-variance 
      slot2.some = new Animal   //legal as some is a var
      slot.get ??
    

    slot.get will then throw an error at runtime as it was unsuccessful in converting an Animal to Dog (duh!).

    In general mutability doesn't go well with co-variance and contra-variance. That is the reason why all Java collections are invariant.

提交回复
热议问题