ace
ace

Reputation: 12044

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?

Upvotes: 8

Views: 8227

Answers (2)

Alois Cochard
Alois Cochard

Reputation: 9862

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

Upvotes: 11

Didier Dupont
Didier Dupont

Reputation: 29548

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).

Upvotes: 15

Related Questions