Optional.ofNullable and method chaining

后端 未结 3 1898
渐次进展
渐次进展 2020-12-05 04:18

I was surprised by Optional.ofNullable method. Some day I wrote a function that supposed to return an Optional:

private Optional          


        
3条回答
  •  盖世英雄少女心
    2020-12-05 04:41

    smth like this should work

    Optional.ofNullable(insight.getValues()).map(vals -> vals.get(0)).map(v -> v.getValue())
    

    well, according to the sample code given, as #extractFirstValueFrom do not contain neither @Nullable nor checks for null like Guava's checkNotNull(), let's assume that insight is always something. thus wrapping Optional.ofNullable(insight.getValues()) into Option would not result with NPE. then call chain of transformations is composed (each results with Optional) that lead to result Optional that might be either Some or None.

提交回复
热议问题