Benjamin M
Benjamin M

Reputation: 24567

java.util.Optional with java.lang.Class - strange behaviour

I tried to do the following:

Class<?> clazz = Optional
        .ofNullable(settingsMap.get(key))
        .map(Object::getClass)
        .orElse(DBObject.class);

Eclipse shows an error on orElse: "The method orElse(Class<capture#12-of ? extends Object>) in the type Optional<Class<capture#12-of ? extends Object>> is not applicable for the arguments (Class<DBObject>)".

Then I tried the following, which works:

Optional<Class<?>> opClazz = Optional
        .ofNullable(settingsMap.get(key))
        .map(Object::getClass);
Class<?> clazz = opClazz.orElse(DBObject.class);

Have I done something wrong? Or is this a bug in Java8?

--

EDIT: Complete example:

Map<String, Object> settingsMap = new HashMap<>();

Class<?> clazz = Optional
        .ofNullable(settingsMap.get(""))
        .map(Object::getClass)
        .orElse(String.class);

Upvotes: 4

Views: 518

Answers (1)

Rafal G.
Rafal G.

Reputation: 4432

This one (below) works well in IntelliJ:

    Map<String, Class<?>> settingsMap = new HashMap<>();

    Class<?> clazz = Optional
            .ofNullable(settingsMap.get(""))
            .map(Object::getClass)
            .orElse(DBObject.class);

Are you sure it is not Eclipse's own compiler failing?

Upvotes: 3

Related Questions