Explicit Java compilation error with raw generic type and Optionals

The following Java code does not compile (using javac 1.8.0_121)

import java.util.Optional;

class B<T> {}

public class Test {
    static B<Integer> f1(B<Object> a) { return null; }

    static B<Integer> f2() {
       Optional<B> opt = Optional.empty(); // note the raw type B
       return opt.map(Test::f1).get();
       // error: incompatible types: Object cannot be converted to B<Integer>
    }
}

My question is: why the code does not compile as above , and why it compiles if I change f1to take a raw type:

static B<Integer> f1(B a) { return null; } // program compiles with raw B

, opt.map Optional<Object> ( Optional<B<Integer>>), ? (JLS 4.8), , (, ). opt , . , ( a raw B B<Object>) ?

Error java: incompatible types: java.lang.Object cannot be converted to B<java.lang.Integer>

+4
1

f1 a ? extends Object, B.

import java.util.Optional;

class B<T> {}

public class Test {
   static B<Integer> f1(B<? extends Object> a) { return null; }

   static B<Integer> f2() {
       Optional<B<?>> opt = Optional.empty(); // note the raw type B
       return opt.map(x -> f1(x)).get();
    }
} 
0

Source: https://habr.com/ru/post/1673822/


All Articles