Collection Method on Scala 2.7

I am looking for a method collectin scala 2.7, but I cannot find a suitable call. Is there something equivalent collectI can use in scala?

To be clear, I am looking to filter items from a list and map the filtered data to a new type.

+3
source share
3 answers

You can use flatMap(full method signature in version 2.7 is equal def flatMap[B](f : (A) => Iterable[B]) : List[B]). It is declared both on Iterableand on Iterator(with slightly different signatures):

scala> val l = List("1", "Hello", "2")
l: List[java.lang.String] = List(1, Hello, 2)

scala> val ints = l.flatMap { s => try { Some(s.toInt) } catch { case _ => None } }
ints: List[Int] = List(1, 2)

In the above example, I am using explicit conversion option2iterableto Predef. It is declared in 2.8 on TraversableLike:

def flatMap[B, That](f: A => Traversable[B])(implicit bf: CanBuildFrom[Repr, B, That]): That
+7
source

flatMap/Option, Chris, , , , :

class Filter[A](f: Any => Option[A]) {
  def unapply(a: Any) = f(a)
}

object Filter {
  def apply[A](f: Any => Option[A]) = new Filter(f)
}

val evens = Filter {
  case n: Int if n % 2 == 0 => Some(n)
  case _ => None
}

:

scala> for (evens(n) <- List.range(0,10)) yield n
res0: List[Int] = List(0, 2, 4, 6, 8)
+7
scala> List(-1,-2, 1,2,3).filter{i => (i % 2) == 0}.map{i => i / 2} 

line10: scala.List[scala.Int] = List(-1,1) 

You need to separate two calls

From a very useful blog

+1
source

Source: https://habr.com/ru/post/1725822/


All Articles