Home > Blockchain >  Wrong object type after stream and filter in Scala: Stream[$_2] instead of Stream[String]
Wrong object type after stream and filter in Scala: Stream[$_2] instead of Stream[String]

Time:05-13

Learning Scala and having some troubles with streams. I'm trying to filter a collection of "Element" (from scala-parser library, kind of all the Soup objects) based on the fact that it contains a "%" and extract the value.

  override def extractRoi(line: Element): Double = {
   line.asInstanceOf[JsoupElement].underlying
  .select("td")
  .stream()
  .map(e => e.text().toString)
  .filter(e => e.contains("%"))
  .findFirst()
  .orElse("")
  .replace("%", "").toDouble
  }

when I map by doing "e.text()" I should have a Stream[String] but it is a Stream[_$2] and I don't understand why. So the code doesn't when at the orElse.

What transformation do I need to do to end up with a Stream[String] ?

CodePudding user response:

It seems that using Java streams in Scala does something weird. In my code above it couldn't infer the right type. So this is how I fixed it:

  override def extractRoi(line: Element): Double = {
   line.select("td")
   .iterator()
   .asScala
   .map(e => e.text().toString)
   .filter(e => e.contains("%"))
   .findFirst()
   .orElse("")
   .replace("%", "").toDouble
  }
  • Related