Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optionally return value from map function

Tags:

scala

map function on collections requires to return some value for each iteration. But I'm trying to find a way to return value not for each iteration, but only for initial values which matches some predicate .

What I want looks something like this:

(1 to 10).map { x =>
   val res: Option[Int] = service.getById(x)
   if (res.isDefined) Pair(x, res.get )// no else part

}

I think something like .collect function could do it, but seems with collect function I need to write many code in guards blocks (case x if {...// too much code here})

like image 274
WelcomeTo Avatar asked Mar 10 '26 15:03

WelcomeTo


2 Answers

If you are returning an Option you can flatMap it and get only the values that are present (that is, are not None).

(1 to 10).flatMap { x =>
   val res: Option[Int] = service.getById(x)
   res.map{y => Pair(x, y) }
}

As you suggest, an alternative way to combine map and filter is to use collect and a partially applied function. Here is a simplified example:

(1 to 10).collect{ case x if x > 5 => x*2 }
res0: scala.collection.immutable.IndexedSeq[Int] = Vector(12, 14, 16, 18, 20)
like image 191
marios Avatar answered Mar 12 '26 05:03

marios


You can use the collect function (see here) to do exactly what you want. Your example would then look like:

(1 to 10) map (x => (x, service.getById(x))) collect {  
  case (x, Some(res)) => Pair(x, res)
}
like image 31
Damien Engels Avatar answered Mar 12 '26 07:03

Damien Engels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!