按名称重复参数 [英] By-name repeated parameters
本文介绍了按名称重复参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Scala中传递重复的参数?
以下代码无法工作:
阶> def foo(s:(=> String)*)= {
< console>:1:error:no这里不允许使用by-name参数类型
def foo(s:(=> String )*)= {
^
是否有其他方式可以传递一个变量号码这是不是很漂亮,但它允许你通过byname参数的方法?
解决方案
/ p>
def printAndReturn(s:String)= {
println(s)
s
}
def foo(s:(Unit => String)*){
println(\\\
In foo)
s foreach {_()} //或者任何你(单位)=> printAndReturn(f1),
(单位)...
}
foo()
foo => printAndReturn(f2))
这产生了
在foo
在foo
f1
f2
How to pass by-name repeated parameters in Scala?
The following code fails to work:
scala> def foo(s: (=> String)*) = {
<console>:1: error: no by-name parameter type allowed here
def foo(s: (=> String)*) = {
^
Is there any other way I could pass a variable number of by name parameters to the method?
解决方案
This isn't very pretty but it allows you to pass byname parameters varargs style
def printAndReturn(s: String) = {
println(s)
s
}
def foo(s: (Unit => String)*) {
println("\nIn foo")
s foreach {_()} // Or whatever you want ...
}
foo()
foo((Unit) => printAndReturn("f1"),
(Unit) => printAndReturn("f2"))
This produces
In foo
In foo f1 f2
这篇关于按名称重复参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文