[英]Seeking clarification regarding type erasure and type inference
class Undoable<T> {
T value;
Deque<Object> history;
Undoable(T t, Deque<Object> history) {
this.value = t;
this.history = history;
}
static <T> Undoable<T> of(T t) {
return new Undoable<T>(t, new LinkedList<Object>());
}
public <R> Undoable<R> flatMap(Function<T, Undoable<R>> mapper) {
Undoable<R> r = mapper.apply(value);
Deque<Object> newHistory = new LinkedList<>();
newHistory.addAll(history);
newHistory.addAll(r.history);
return new Undoable<R>(r.value, newHistory);
}
public <R> Undoable<R> undo() {
Deque<Object> newHistory = new LinkedList<>(this.history);
R r;
try {
r = (R)newHistory.removeLast(); //line A
} catch (NoSuchElementException e) {
throw new CannotUndoException();
}
return new Undoable<R>(r, newHistory);
}
}
鑒於上面的代碼片段,假設我們保持 A 行不變並忽略編譯警告。 如果我們會發生什么
Undoable<Integer> i = Undoable.of("hello").flatMap(s -> {
Deque<Object> history;
history = new LinkedList<>();
history.add(s);
return new Undoable<Integer>(s.length(), history);
});
Undoable<Double> d = i.undo();
我得到Undoable<Integer>
和Undoable<Double>
擦除為Undoable
。 但是undo()
方法中的R
會變成什么? 它是否推斷為Double
因為Double
是該方法調用的目標類型?
我試過在我的機器上運行代碼,它運行良好,但我不知道為什么。 任何人都可以解釋一下嗎? 萬分感謝!
The R
type it will become Object
, even when inferred during the method call, this is because of R
been of no use, since you never explicit declared it, like this i.<Double>undo()
, in most use cases, parametric在方法中使用類型來推斷方法參數的類型。 關於您的代碼流,即使使用 Undone d.value
也是一個字符串,這是因為d
Undone
類型將被編譯為 object,因為R
類型可以是任何東西,沒有如何比較,在編譯時,類型使用您的聲明推斷方法調用的結果。 如果你把Undone<Double> d = i.<String>undo()
它會拋出一個錯誤,否則如果你不顯式聲明,永遠不會拋出一個強制轉換異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.