What is a capture conversion in Java and can anyone give me examples?

前端 未结 2 1198
小蘑菇
小蘑菇 2020-12-01 10:56

I\'ve noticed JLS talks of 5.1.10 Capture Conversion, but I fail to understand what they are.

Can anyone explain them to me/give examples?

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 11:36

    A parameterized type involving wildcard type arguments is really a union type. For example

    List = Union{ List | S <: Number }
    

    In 2 cases, instead of using List, Java uses the captured version List, where S is a just-created type variable with upper bound Number.

    (1) http://java.sun.com/docs/books/jls/third_edition/html/expressions.html

    To narrow the type of an expression. If an expression's type is List, we know for sure that the runtime type of the object is actually a List for some concrete type S (S <: Number>). So compiler uses List instead, to perform more accurate type analysis.

    Capture conversion is applied to each expression individually; this leads to some dumb results:

     void test1(List a){}
     void test2(List a, List b){}
    
    List x = ...;
    test1(x);    // ok
    test2(x, x); // error
    

    (2) http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.10.2

    In subtype checking A :< B where A involves wildcard arguments. For example,

    List  :< B
    <=>
    Union{ List | S <: Number}  :< B
    <=>
    List :< B, for all S <: Number
    

    So in effect, we are checking the captured version of type A

提交回复
热议问题