我对scala编程很陌生,想写一个函数,通过传入的参数返回一个元组实例。这就是我的意思:
def toTuple(strings : String*) = {
//some code to create a tuple, if possible
//the tuple should be consistent with the order the arguments were passed in
}
是否可以在scala中执行此操作?
答案 0 :(得分:1)
问题在于返回此功能的类型。它应该是什么?任何?但这听起来不像是一个好的静态打字。我建议你使用类似的东西:
def toTuple(strings : String*): (String, String) = strings.toList match{
case Nil => ("", "")
case a :: Nil => (a, "")
case a :: b :: xs => (a, b)
}
用法:
scala> toTuple(List("a"): _*)
res2: (String, String) = (a,"")
scala> toTuple(List("a", "b"): _*)
res3: (String, String) = (a,b)