Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better version of "iterate over Seq or if empty" in scala?

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 ;)

like image 318
i.am.michiel Avatar asked Aug 21 '12 08:08

i.am.michiel


2 Answers

How about this?

mySeq.headOption.map { _ =>
  mySeq.map { elmt => 
    // do stuff
  }
}.getOrElse {
  // some other stuff
}
like image 64
Jean-Philippe Pellet Avatar answered Oct 07 '22 03:10

Jean-Philippe Pellet


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)
like image 7
senia Avatar answered Oct 07 '22 03:10

senia