When is @uncheckedVariance needed in Scala, and why is it used in GenericTraversableTemplate?

前端 未结 3 1320
臣服心动
臣服心动 2020-12-02 14:20

@uncheckedVariance can be used to bridge the gap between Scala\'s declaration site variance annotations and Java\'s invariant generics.

scala>         


        
3条回答
  •  执笔经年
    2020-12-02 14:58

    The problem is that GenericTraversableTemplate is used twice: once for mutable collections (where its type parameter should be invariant), and once for immutable collections (where covariance is invariably king).

    GenericTraversableTemplate's typechecks assuming either covariance or invariance for the A type parameter. However, when we inherit it in a mutable trait, we have to pick invariance. Conversely, we'd like covariance in an immutable subclass.

    Since we can't abstract over the variance annotation (yet ;-)) in GenericTraversableTemplate, so that we could have instantiated it to either one depending on the subclass, we have to resort to casting (@uncheckVariance is essentially a kind-cast). For further reading, I recommend my dissertation (sorry ;-)) or our recent bitrot paper

提交回复
热议问题