比方说,我有这个功能。如何将字符串的元组转换为字符串*?
def foo(bar: String*): String = { bar.mkString(", ") }
它可以将一个或多个字符串值作为参数。
scala> foo("hello", "world", "foo")
res4: String = hello, world, foo
但是,我该如何做到这一点,以下也适用。
scala> foo(("hello", "world", "foo"))
<console>:26: error: type mismatch;
found : (String, String, String)
required: String
foo(("hello", "world", "foo"))
^
可以作为参数传递的字符串的数量可以是任意的。为什么我需要这个是因为,我有另一种方法。
def fooHelper() = {
("hello", "world", "foo") // Again, can be arbitrary number
}
我想这样使用。
foo(fooHelper())
我不认为这是来自未知元数的元组调用可变参数的函数的通用方法。它可以使用列表值和':_ *'完成。否则,你可以看看无定形,这允许更通用。 – cchantep