Java.util.Optional with java.lang.Class - weird behavior

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: it works :

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

Did I do something wrong? Or is this a bug in Java8?

-

EDIT: full example:

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

Class<?> clazz = Optional
        .ofNullable(settingsMap.get(""))
        .map(Object::getClass)
        .orElse(String.class);
+4
source share
1 answer

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 that your own Eclipse compiler is not compiled?

+3
source

All Articles