[英]Chained Optional.map calls cause compilation error
我正在嘗試Java 8 Optional
類:
static Optional<Integer> test() {
return Optional.of(1).map(i -> Optional.of(i.toString()).map(j -> Integer.valueOf(j)));
}
在我看來,該函數應該返回一個可選的Integer對象1。但是Java 8編譯器並不滿意:
Test.java:5: error: incompatible types: inference variable U has incompatible bounds
return Optional.of(1).map(i -> Optional.of(i.toString()).map(j -> Integer.valueOf(j)));
^
equality constraints: Integer
lower bounds: Optional<U>
where U,T are type-variables:
U extends Object declared in method <U>map(Function<? super T,? extends U>)
T extends Object declared in class Optional
為什么編譯器不滿意?
Optional
的.map()
的簽名表明,作為參數給出的Function
返回U
,而不是Optional<U>
; 此方法將包裝U
本身。
因此,您必須:
Optional.of(1).map(i -> i.toString()).map(j -> Integer.parseInt(j))
(注意:同樣, Integer.valueOf()
並非您的意思;它不使用String
作為參數)
最后,兩個lambda都可以替換為方法引用:
Optional.of(1).map(Object::toString).map(Integer::parseInt)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.