How to cast each element in Scala List?
I have an API (from third party java library) that looks开发者_如何转开发 like:
public List<?> getByXPath(String xpathExpr)
defined on a class called DomNode
I want to do something like to get Scala List in which each item is of the specified type:
val txtNodes: List[DomText] = node.getByXPath(xpath).toList
But compiler gives error: type mismatch.
what is the solution to this problem?
You need to cast each element of the list, to prove all of them have the required type. You can do that just when iterating, for instance
node.getByXPath(xpath).map{case d: DomText => d}.toList
or
node.getByXPath(xpath).map(_.asInstanceOf[DomText]).toList
whichever writing of the cast suits you better.
You could also cast the list, node.getByXPath(xPath).toList.asInstanceOf[List[DomText]]
, but you would get a warning, as this cast is done without any check because of type erasure (just as in java).
Since Scala 2.8, you can use 'collect':
scala> "hi" :: 1 :: "world" :: 4 :: Nil collect {case s:String => s}
res13: List[String] = List(hi, world)
Source: http://daily-scala.blogspot.com/2010/04/filter-with-flatmap-or-collect.html
精彩评论