Mahdi
Mahdi

Reputation: 1852

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")
}

Upvotes: 0

Views: 608

Answers (1)

Shadowlands
Shadowlands

Reputation: 15074

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

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

Upvotes: 4

Related Questions