比方說,我有這個功能。如何將字符串的元組轉換爲字符串*?
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