Is there a shorter/better way to do the following :
mySeq.map { elmt =>
// do stuff
}
if (mySeq.isEmpty) {
// some other stuff
}
Ps : I'm using PlayFramework and this is meant to be used in templates, so if there are any "helpers" there I missed, I would be glad to discover those ;)
How about this?
mySeq.headOption.map { _ =>
mySeq.map { elmt =>
// do stuff
}
}.getOrElse {
// some other stuff
}
You can use match
:
l match {
case l if !l.isEmpty => l.map{ // do stuff }
case _ => // some other stuff
}
For List
:
l match {
case h :: t => l.map{ // do stuff }
case _ => // some other stuff
}
Alternatively you can define your own method:
import scala.collection.generic.CanBuildFrom
import scala.collection.TraversableLike
class FoldEmpty[T, S[T] <: TraversableLike[T, S[T]]](l: S[T]){
def foldEmpty[B, That](notEmpty: T => B, empty: => That)(implicit cbf: CanBuildFrom[S[T], B, That]): That =
l match {
case t if !t.isEmpty => l map notEmpty
case _ => empty
}
}
implicit def seqToFoldEmpty[T, S[T] <: TraversableLike[T, S[T]]](l: S[T]) = new FoldEmpty(l)
Usage:
scala> IndexedSeq(1, 2, 3).foldEmpty( _ + 1 , IndexedSeq(-1))
res0: IndexedSeq[Int] = Vector(2, 3, 4)
scala> IndexedSeq[Int]().foldEmpty( _ + 1 , Seq(-1))
res1: Seq[Int] = List(-1)
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