2011-06-15 22 views
0

我有一個API(來自第三方Java庫),看起來像:遍歷Java列表,涉及Java泛型斯卡拉

public List<?> getByXPath(String xpathExpr) 

defined on a class called DomNode 

我試試這個斯卡拉:

node.getByXPath(xpath).toList.foreach {node: DomElement => 

    node.insertBefore(otherNode) 

} 

但node.getByXPath上出現編譯錯誤。 錯誤: 「類型不匹配;實測值:(com.html.DomElement)=>所需單位:=>其中類型0(0?)?」

如果我改變成:

node.getByXPath(xpath).toList.foreach {node => 

    node.insertBefore(otherNode) 

} 

然後錯誤消失,但然後我得到錯誤node.insertBefore(otherNode) 錯誤:「值insertBefore不是?0的成員」

這個問題的答案是什麼?

回答

1

你必須施放它。即

node.getByXPath(xpath).toList.foreach {node => 
    node.asInstanceOf[DomElement].insertBefore(otherNode) 
} 

在Java中,您會遇到與List元素的類型未知相同的問題。

(我假設每個元素實際上是一個DOMElement)

編輯:

丹尼爾是正確的,有一個更好的方式來做到這一點。例如,您可以拋出更好的異常(與ClassCastException或MatchError相比)。例如。

node.getByXPath(xpath).toList.foreach { 
    case node: DomElement => node.insertBefore(otherNode) 
    case _: => throw new Exception("Expecting a DomElement, got a " + node.getClass.getName) 
} 
6

這樣做:

node.getByXPath(xpath).toList.foreach { 
    case node: DomElement => node.insertBefore(otherNode) 
} 

使用case,你把它變成一個模式匹配功能。如果有任何非DomElement返回,您將得到一個異常 - 如果有必要,您可以添加另一個case匹配以處理默認情況。

不應該做的是用asInstanceOf。這就拋棄了任何類型的安全性,只有很少的收穫。

+1

這是一個很好的觀點,至少在部分功能方面,如果它不是DomElement,您有機會做某些事情。但是,如果你不提供另一個'case',它基本上與演員相當 - 如果它不是預期的類型,你會得到一個異常。 – sourcedelica 2011-06-16 04:55:10