2011-06-15 24 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