2016-02-25 119 views
1

比方说,我有这个功能。如何将字符串的元组转换为字符串*?

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

我不认为这是来自未知元数的元组调用可变参数的函数的通用方法。它可以使用列表值和':_ *'完成。否则,你可以看看无定形,这允许更通用。 – cchantep

回答

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 

另外,作为支持阶元组只到22元,你可以写(生成)自己展开帮手。

3

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

使用像

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

相关问题