29 Aralık 2020 Salı

Optional.orElseGet metodu - Supplier Kullanır

Giriş
Açıklaması şöyle.
This method returns the value if present. Otherwise, it invokes other and returns the result of the invocation.
Optional boş değilse taşıdığı değeri, boşsa belirtilen supplier çağrısının sonucunu döner.
İmzası şöyle
public T orElseGet(Supplier<? extends T> supplier)
//If a value is present, returns the value, otherwise returns the result produced by the
//supplying function.
//Parameters:
//supplier - the supplying function that produces a value to be returned
//Returns:
//the value, if present, otherwise the result produced by the supplying function
//Throws:
//NullPointerException - if no value is present and the supplying function is null
orElse() ile Farkı
orElseGet() lazy çalışır. orElse() ise lazy değildir
Elimizde şöyle bir kod olsun. constructTableFromCache() null dönmese dahi, fetchTableFromRemote() çalıştırılır
public Optional<Table> retrieveTable() {
  return Optional.ofNullable(constructTableFromCache())
                 .orElse(fetchTableFromRemote());
}
Bunu engellemek için şöyle yaparız
public Optional<Table> retrieveTable() {
return Optional.ofNullable(constructTableFromCache()) .orElseGet(this::fetchTableFromRemote); }
Örnek
Şöyle yaparız.
return stuff().that().returns().optional().orElseGet(() -> {
    ...
    return alternateResult;
});

Hiç yorum yok:

Yorum Gönder