如何将String的元组转换为String *?

时间:2016-02-25 23:43:12

标签: scala

让我们说,我有这个功能。

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())

2 个答案:

答案 0 :(得分:3)

不使用外部库的简单解决方案是使用productIterator将元组转换为迭代器。

使用

foo(("a", "b").productIterator.toList.map(_.toString):_*)

答案 1 :(得分:1)

可以使用shapeless库完成此操作:

> import shapeless._
> import syntax.std.tuple._

> def foo(any: Any *) = { any.foreach(println) }
defined function foo

> foo((23, "foo", true).toList:_*)
23
foo
true

此外,由于scala仅支持最多22个元素的元组,因此您可以自己编写(生成)解包帮助。

相关问题