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

前端 未结 3 1346
臣服心动
臣服心动 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 15:01

    I found another time where @uncheckedVariance is used -- the synthetic method that returns the default value for a parameter of an abstract type:

    M:\>scala -Xprint:typer -e "class C { def p[T >: Null](t: T = null) = t }"
    [[syntax trees at end of typer]]// Scala source: (virtual file)
    package  {
      final object Main extends java.lang.Object with ScalaObject {
        def this(): object Main = {
          Main.super.this();
          ()
        };
        def main(argv: Array[String]): Unit = {
          val args: Array[String] = argv;
          {
            final class $anon extends scala.AnyRef {
              def this(): anonymous class $anon = {
                $anon.super.this();
                ()
              };
              class C extends java.lang.Object with ScalaObject {
                 def p$default$1[T >: Null <: Any]: Null @scala.annotation.unchecked.uncheckedVariance = null;
                def this(): this.C = {
                  C.super.this();
                  ()
                };
                def p[T >: Null <: Any](t: T = null): T = t
              }
            };
            {
              new $anon();
              ()
            }
          }
        }
      }
    

提交回复
热议问题