Type Members and Covariance

前端 未结 1 1265
滥情空心
滥情空心 2021-02-08 04:26

I guess, \"type variance annotations\" (+ and -) cannot be applied to \"type members\". In order to explain it to myself I considered the following exa

相关标签:
1条回答
  • 2021-02-08 04:36

    Box is invariant in its type T, but that doesn't mean there's nothing to see.

    abstract class Box {
      type T
      def get: T
    }
    type InvariantBox = Box { type T = AnyRef }
    type SortofCovariantBox = Box { type T <: AnyRef }
    

    What alters the variance situation is the degree to which the type is exposed and the manner it is done. Abstract types are more opaque. But you should play with these issues in the repl, it's quite interesting.

    # 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)
    

    And etc.

    0 讨论(0)
提交回复
热议问题