将List的元素作为参数传递给具有可变参数的函数

编程入门 行业动态 更新时间:2024-10-23 06:22:40
本文介绍了将List的元素作为参数传递给具有可变参数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

例如,我有一个名为或的函数,它被定义为;

或(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的元素作为参数传递给具有可变参数的函数

本文发布于:2023-07-29 08:57:38,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   函数   元素   List

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!