Search code examples
scalafor-comprehensionempty-list

Scala for comprehension with special treatment of empty list


Is there a more functional way of doing the following?

if (myList.isEmpty) {
    println("Empty list")
} else for (element <- myList) {
    println(element)
}

Maybe something like:

for (element <- myList) {
    println(element)
} orElse {
    println("Empty list")
}

Solution

  • What you have seems fine, but one variation might be:

    myList match {
      case Nil => println("Empty list")
      case _ => myList.foreach(println)
    }