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?
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.
::: - concatenates two lists and returns the concatenated list.
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.
In order to concatenate two lists we need to utilize concat() method in Scala. In above syntax, l1 is list1 and l2 is list2.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With