Reputation: 3623
In scala, is there an idiomatic way to specify default value for collections when it's empty?
For Option
s, you could use .getOrElse
.
I'm thinking something like below:
Seq().ifEmpty(Seq("aa", "bb")) // Seq("aa", "bb")
Seq("some", "value").ifEmpty(Seq("aa", "bb")) // Seq("some", "value")
Upvotes: 4
Views: 3330
Reputation: 22374
The cleanest way for scala (without scalaz) seems to be:
Option(list).filter(_.nonEmpty).getOrElse(List(1,2,3))
Upvotes: 4
Reputation: 22374
You may try scalaz's toNel
(to Non-empty list) - it will give you Some(collection)
for non-empty collection and None
for empty collection, so you can do list.toNel.getOrElse(List(1))
:
scala> import scalaz._; import Scalaz._
import scalaz._
import Scalaz._
scala> List(1, 2, 3).toNel
res8: Option[scalaz.NonEmptyList[Int]] = Some(NonEmptyList(1, 2, 3))
scala> nil[Int].toNel
res9: Option[scalaz.NonEmptyList[Int]] = None
nil[Int]
means List[Int]()
here.
Src: http://docs.typelevel.org/api/scalaz/stable/6.0/doc.sxr/scalaz/ListW.scala.html
Upvotes: 0
Reputation: 18869
Is this OK?
scala> val seq = "ABCDEFG".toIndexedSeq
seq: scala.collection.immutable.IndexedSeq[Char] = Vector(A, B, C, D, E, F, G)
scala> seq(3)
res0: Char = D
scala> val ept = Seq.empty[Char]
ept: Seq[Char] = List()
scala> ept(3)
java.lang.IndexOutOfBoundsException: 3
at scala.collection.LinearSeqOptimized$class.apply(LinearSeqOptimized.scala:51)
at scala.collection.immutable.List.apply(List.scala:83)
... 32 elided
scala> ept.orElse(seq)(3)
res3: Char = D
OR
scala> ept.applyOrElse(3, "abcdef")
res4: Char = d
Upvotes: 1