例如,我有一个名为或的函数,它被定义为;
或(filters:FilterDefinition *)然后我有一个列表:
列表(X,Y,Z)我现在需要做的是调用或,比如
或(func(X),func(Y),func(Z))和预期的一样,列表的长度可能会改变。
在Scala中执行此操作的最佳方式是什么?
解决方案code> def printme(s:String *)= s.foreach(println) scala> printme(List(a,b,c)) < console>:9:error:type mismatch; found:List [String] required:String printme(List(a,b,c))
你真的需要用解开列表参数:_ * 操作符
scala> val mylist = List(1,2,3) scala> printme(mylist:_ *) 1 2 3
I have a function called or for example, which is defined as;
or(filters: FilterDefinition*)And then I have a list:
List(X, Y, Z)What I now need to do is call or like
or(func(X), func(Y), func(Z))And as expected the length of the list may change.
What's the best way to do this in Scala?
解决方案Take a look at this example, I will define a function printme that takes vargs of type String
def printme(s: String*) = s.foreach(println) scala> printme(List("a","b","c")) <console>:9: error: type mismatch; found : List[String] required: String printme(List(a,b,c))What you really need to un-pack the list into arguments with the :_* operator
scala> val mylist = List("1","2","3") scala> printme(mylist:_*) 1 2 3
更多推荐
将List的元素作为参数传递给具有可变参数的函数
发布评论