我目前正在学习Scala,感到非常惊奇。这种语言可以优雅地解决许多问题。但是,在匹配列表的最后一个元素时,我遇到了一个问题。
让我们来看一下这段代码:
def stringify(list: List[String]): String = list match {
case x :: xs => x + (if (xs.length != 0) ":" else "") + stringify(xs)
case Nil => ""
}
这样做非常不优雅,我希望写出更直观的代码,像这样:
def stringify(list: List[String]): String = list match {
case x :: xs => x + ":" + stringify(xs)
case x :: Nil => x
}
我该怎么做?