我有一个API(来自第三方java库),看起来像:
public List<?> getByXPath(String xpathExpr)
defined on a class called DomNode
Run Code Online (Sandbox Code Playgroud)
我在scala中尝试这个:
node.getByXPath(xpath).toList.foreach {node: DomElement =>
node.insertBefore(otherNode)
}
Run Code Online (Sandbox Code Playgroud)
但是我在node.getByXPath上遇到编译错误.错误:"类型不匹配;找到:(com.html.DomElement)=>所需单位:(?0)=>?其中type?0"
如果我将其更改为:
node.getByXPath(xpath).toList.foreach {node =>
node.insertBefore(otherNode)
}
Run Code Online (Sandbox Code Playgroud)
然后错误消失但是我在node.insertBefore(otherNode)错误上得到错误:"value insertBefore不是?0的成员"
这个问题的答案是什么?
做这个:
node.getByXPath(xpath).toList.foreach {
case node: DomElement => node.insertBefore(otherNode)
}
Run Code Online (Sandbox Code Playgroud)
通过使用case
,您可以将其转换为模式匹配功能.如果返回任何非DomElement,您将获得异常 - case
如果需要,您可以为默认大小写添加另一个匹配项来处理它.
你不应该做的是使用asInstanceOf
.抛弃任何类型的安全,几乎没有收获.