Scala:模式匹配+字符串连接

Fra*_*itt 0 scala concatenation pattern-matching

我有一个简单的递归函数将布尔值列表转换为字符串:

def boolsToString(lst: List[Boolean]): String = lst match {
    case Nil => ""
    case x::xs => x match {
      case false => "0" + boolsToString(xs)
      case true => "1" + boolsToString(xs)
    }
  }
Run Code Online (Sandbox Code Playgroud)

这可行,但我不喜欢重复 boolsToString。我只想进行一次字符串连接(在大小写之后):

  def boolsToString2(lst: List[Boolean]): String = lst match {
    case Nil => ""
    case x::xs => x match {
      case false => "0"
      case true => "1"
    } + boolsToString2(xs)
  }
Run Code Online (Sandbox Code Playgroud)

但这被 Scala 编译器拒绝:“';' 符合预期,但找到了标识符。”

在这种情况之后,还有另一种方法可以只进行一次字符串连接吗?

Sto*_*ica 5

无需重新发明轮子。Iterables 已经有一个将项目连接到字符串中的方法,称为mkString

def boolsToString(lst: List[Boolean]) =
  lst.map(if(_) "1" else "0").mkString("")
Run Code Online (Sandbox Code Playgroud)