val init = l.view.init
val result =
if (init.nonEmpty) {
init.mkString(", ") + " and " + l.last
} else l.headOption.getOrElse("")
init
returns all elements except the last one, view
allows you to get init
without creating a copy of collection.
For empty collection head
(and last
) will throw an exception, so you should use headOption
and lastOption
if you can't prove that your collection is not empty.