Comment retourner quand un optionnel est vide?

J'aime que options sont dans la norme Java bibliothèque aujourd'hui. Mais il y a un problème de base je continuer à courir dans lequel je n'ai pas trouvé comment le résoudre dans les meilleurs (plus facile à lire et à comprendre, la plus jolie, la plus courte):

Comment retourner à partir d'une méthode lorsqu'une option est vide?

Je suis à la recherche d'une solution générale qui travaille pour différentes combinaisons de nombres d'options et de tailles de blocs de code.

Dans les exemples qui suivent, je vais essayer de montrer ce que je veux dire:

void m1() {
    //When I get an optional:
    Optional<String> o = getOptional();

    //And want to return if it's empty
    if (!o.isPresent()) return;

    //In the whole rest of the method I have to call Optional.get 
    //every time I want the value:
    System.out.println(o.get());

    //Which is pretty ugly and verbose!
}


void m2() {
    //If I instead return null if a value is absent:
    String s = getNullabe();
    if (s == null) return;

    //Then I can use the value directly:
    System.out.println(s);
}

Cette question est de savoir comment tirer le bon aspect des deux exemples ci-dessus: Le type en toute sécurité de l'option et la brièveté de types nullables.

Le reste des exemples qui illustre ce plus.

void m3() {
    //If I on the other hand want to throw on empty that's pretty and compact:
    String s = getOptional()
        .orElseThrow(IllegalStateException::new);

    System.out.println(s);
}

void m4() {
    Optional<String> o = getOptional();
    if (!o.isPresent()) return;

    //I can of course declare a new variable for the un-optionalised string:
    String s = o.get();

    System.out.println(s);

    //But the old variable still remains in scope for the whole method 
    //which is ugly and annoying.
    System.out.println(o.get());
}


void m5() {
    //This is compact and maybe pretty in some ways:
    getOptional().ifPresent(s -> {
        System.out.println(s);

        //But the extra level of nesting is annoying and it feels 
        //wrong to write all the code in a big lambda.

        getOtherOptional().ifPresent(i -> {
            //Also, more optional values makes it really weird and 
            //pretty hard to read,  while with nullables I would 
            //get no extra nesting, it would looks good and be 
            //easy to read.
            System.out.println("i: " + i);

            //It doesn't work in all cases either way.
        });
    });
}


Optional<String> getOptional() {
    throw new UnsupportedOperationException();
}

Optional<Integer> getOtherOptional() {
    throw new UnsupportedOperationException();
}

String getNullabe() {
    throw new UnsupportedOperationException();
}

Comment puis-je retourner à partir d'une méthode si une option est vide, sans avoir à utiliser get dans le reste de la méthode, sans déclarer une variable supplémentaire et sans niveaux supplémentaires de bloc de nidification?

Ou s'il n'est pas possible d'obtenir tout cela, quelle est la meilleure façon de gérer cette situation?

source d'informationauteur Lii