簡體   English   中英

是否有一種優雅的方式來展開包裝在2個嵌套的Optionals中的對象?

[英]Is there an elegant way to unwrap an object wrapped in 2 nested Optionals?

考慮這兩個類

class EmailService {
    public Optional<String> getEmailAlias(String email);
}

enum Queue {
    public static Optional<Queue> fromEmailAlias(String alias);
}

上述方法的實現對於這個問題並不重要,所以為了簡單起見,我把它留了下來。

我想做這個:

emailService.getEmailAlias("john@done")
    .map(Queue::fromEmailAlias)
    .ifPresent(queue -> { 
        // do something with the queue instance, oh wait it's an Optional<Queue> :(
    });

但是,這不起作用,因為queue的類型為Optional<queue> (與Queue::fromEmailAlias返回的類型相同),所以我改為:

emailService.getEmailAlias("john@done")
    .map(Queue::fromEmailAlias)
    .ifPresent(q-> { 
            q.ifPresent(queue -> {
                // do something with the queue instance
            }
    });

一種丑陋的imho。

改變簽名

public static Optional<Queue> fromEmailAlias(String alias);

public static Queue fromEmailAlias(String alias);

是一個快速修復,但這也會影響我需要Optional<Queue>其他地方的代碼。

有沒有一種很好的方法來解開這個嵌套的Optional?

您需要應用flatMap

emailService.getEmailAlias("john@done")
            .flatMap(Queue::fromEmailAlias)
            .ifPresent(queue -> { 

             });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM