具有可变参数的模式匹配

时间:2019-06-30 18:07:57

标签: scala pattern-matching

请最好建议实施以下代码:

要求:传递单个字符串或不传递参数

object Twofer {
  def twofer(name: String*): String = name match {
    case Seq(nm) => s"One for $nm, one for me."
    case List() => "One for you, one for me."
  }
}

1 个答案:

答案 0 :(得分:3)

也许类似于以下内容:

def twofer(names: String*): String = List(names: _*) match {
  case Nil => "No names!"
  case n :: Nil => s"Single name $n"
  case ls => s"Multiple names $ls"
}