在Scala中迭代涉及Java泛型<! - ? - >的java List

时间:2011-06-15 23:39:05

标签: scala

我有一个API(来自第三方java库),如下所示:

public List<?> getByXPath(String xpathExpr)

defined on a class called DomNode

我在scala中尝试这个:

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

   node.insertBefore(otherNode)   

}

但是我在node.getByXPath上遇到编译错误。 错误:“类型不匹配;找到:(com.html.DomElement)=&gt;所需单位:(?0)=&gt;?其中type?0”

如果我将其更改为:

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

   node.insertBefore(otherNode)   

}

然后错误消失但是我在node.insertBefore(otherNode)上得到错误 错误:“值insertBefore不是?0”的成员

这个问题的答案是什么?

2 个答案:

答案 0 :(得分:6)

这样做:

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

通过使用case,您可以将其转换为模式匹配功能。如果返回任何非DomElement,您将获得异常 - 如果需要,您可以为默认情况添加另一个case匹配项来处理它。

不应该做的是使用asInstanceOf。抛弃任何类型的安全,几乎没有收获。

答案 1 :(得分:1)

你必须施展它。即,

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

在Java中你会遇到同样的问题,因为List元素的类型是未知的。

(我假设每个元素实际上都是一个DomElement)

编辑:

Daniel是对的,有更好的方法可以做到这一点。例如,您可以抛出一个更好的异常(与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)   
}