Scala List match last element

pattern-matching, scala

Solution

You need to switch the order. The `xs` symbol will eagerly match anything in that position. Trying to match `Nil` first will make that statement no longer unreachable. Also, you'll still need to match `Nil` by itself to account for empty lists.

def stringify(list: List[String]): String = list match {
   case x :: Nil => x
   case x :: xs => x + ":" + stringify(xs)  
   case Nil => ""
}

Though `mkString` already does what you're looking to make.

Problem

I'm currently learning Scala and I'm amazed. The language handles so much problems quite elegant. But, I got a problem when it comes to matching the last element of a list. Let's have a look at this code: ``` def stringify(list: List[String]): String = list match { case x :: xs => x + (if (xs.length != 0) ":" else "") + stringify(xs) case Nil => "" } ``` This is quite inelegant and I would like to write it more intuitive, something like this: ``` def stringify(list: List[String]): String = list match { case x :: xs => x + ":" + stringify(xs) case x :: Nil => x } ``` How can I do that?

Original source