Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast each element in Scala List?

Tags:

scala

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?

like image 421
ace Avatar asked Jun 16 '11 12:06

ace


People also ask

How do you cast in Scala?

Type Casting in Scala is done using the asInstanceOf[] method. This perspective is required in manifesting beans from an application context file. It is also used to cast numeric types.

What does ::: mean in Scala?

::: - concatenates two lists and returns the concatenated list.

Can you index a list in Scala?

Scala List indexOf() method with example. The indexOf() method is utilized to check the index of the element from the stated list present in the method as argument. Return Type: It returns the index of the element present in the argument.

How do you concatenate lists in Scala?

In order to concatenate two lists we need to utilize concat() method in Scala. In above syntax, l1 is list1 and l2 is list2.


2 Answers

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

like image 165
Didier Dupont Avatar answered Sep 22 '22 00:09

Didier Dupont


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

like image 42
Alois Cochard Avatar answered Sep 21 '22 00:09

Alois Cochard