scala splat 可以用于任何不是可变参数的东西吗?
给定例如:
scala> def pipes(strings:String*) = strings.toList.mkString("|")
我可以正常调用:
scala> pipes("foo", "bar")
res1: String = foo|bar
或使用 splat:
scala> val args = List("a","b","c")
scala> pipes(args:_*)
res2: String = a|b|c
但是我可以使用 splat 为除 varargs 参数之外的任何参数提供参数吗?例如,我想做类似的事情:
scala> def pipeItAfterIncrementing(i:Int, s:String) = (i + 1) + "|" + s
scala> val args:Tuple2[Int, String] = (1, "two")
scala> pipeItAfterIncrementing(args:_*)
这不起作用,但是有什么方法可以达到从单个对象提供多个参数的相同效果,无论它是元组还是其他东西?鉴于元组的长度和类型在编译时已知,是否有任何原因无法对元组实现?
given e.g:
scala> def pipes(strings:String*) = strings.toList.mkString("|")
which I can call normally:
scala> pipes("foo", "bar")
res1: String = foo|bar
or with a splat:
scala> val args = List("a","b","c")
scala> pipes(args:_*)
res2: String = a|b|c
But can I use a splat to provide arguments for anything but a varargs parameter? e.g I would like to do something like:
scala> def pipeItAfterIncrementing(i:Int, s:String) = (i + 1) + "|" + s
scala> val args:Tuple2[Int, String] = (1, "two")
scala> pipeItAfterIncrementing(args:_*)
That doesn't work, but is there any way to achieve the same effect of providing multiple arguments from a single object, whether it be a tuple or something else? Is there any reason this couldn't be implemented for tuples, given that both their length and types are known at compile-time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 Function.tupled 来完成此操作:将采用 n 个参数的函数转换为采用元数 n 的单个元组参数的函数>。正如所预料的,Function.untupled 执行相反的工作。
特殊类型归属
: _*
仅适用于重复参数(又名可变参数)。You can use
Function.tupled
to do exactly this: turn a function that takes n arguments into a function that takes a single tuple argument of arity n. As can be expected,Function.untupled
does the reverse job.The special type ascription
: _*
is only applicable for repeated parameter (a.k.a. varargs).嗯……
会给你想要的
2|two
。Well kind of ...
will give you the desired
2|two
.