How does Java's use-site variance compare to C#'s declaration site variance?

前端 未结 4 1587
耶瑟儿~
耶瑟儿~ 2020-12-01 03:22

My understand is that specifying variance for generics in C# happens at the type declaration level: when you\'re creating your generic type, you specify the variance for the

4条回答
  •  借酒劲吻你
    2020-12-01 04:17

    Java: Use-site variance generics since Java 5. Broken covariant arrays with a different syntax since 1.0. No runtime type info of generics.

    C#: Use-site variance generics since C# 2.0. Added declaration site variance in C# 4.0. Broken covariant arrays with a different syntax since 1.0 (identical issue to Java). "reified" generics meaning that type info isn't lost at compilation time.

    Scala: Both use-site/declaration-site variance since early versions of the language (at least since 2008). Arrays are not a separate language feature, so you use the same generics syntax and type variance rules. Certain collections are implemented at the VM level with JVM arrays so you get equal or better runtime performance compared with Java code.

    To elaborate on the C#/Java array type safety problem: You can cast a Dog[] to a Pet[] and add a Cat and trigger a runtime error that isn't caught at compilation time. Scala implemented this correctly.

提交回复
热议问题