Variance annotations in type aliases

后端 未结 2 912
梦谈多话
梦谈多话 2020-12-31 07:26

Recently I\'ve noticed that variance annotations can be used in type aliases. Here is example from Predef:

type Function[-A, +B] = Function1[A,          


        
2条回答
  •  暖寄归人
    2020-12-31 07:55

    If the abstract type is only declared (as in Domain), the invariance will be enforced. If the abstract type is defined to have a more relaxed variance, this is respected once known (as in DomainImpl):

    trait Domain {
      type InvList[T]
    
      val xi: InvList[Int]
      private val xa: InvList[Any] = xi // won't compile
    }
    
    class DomainImpl extends Domain {
      type InvList[T] = List[T]
    
      val xi: InvList[Int] = List(1)
      private val xa: InvList[Any] = xi // will compile
    }
    

提交回复
热议问题