Specify a default value for collections

In scala, is there an idiomatic way to specify a default value for collections when empty?

For Option

s, you can use .getOrElse

. I think something like below:

Seq().ifEmpty(Seq("aa", "bb")) // Seq("aa", "bb")
Seq("some", "value").ifEmpty(Seq("aa", "bb")) // Seq("some", "value")

      

+3


source to share


3 answers


The cleanest way for scala (no scalar) is as follows:



Option(list).filter(_.nonEmpty).getOrElse(List(1,2,3))

      

+3


source


This is normal?

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

      

+1


source


You can try scalaz toNel

(to N on e mpty l ist) - it will give you Some(collection)

for a non-empty collection and None

for an 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

0


source







All Articles