加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 如何使用Array [String]元素调用String *的方法

发布时间:2020-12-16 18:24:02 所属栏目:安全 来源:网络整理
导读:假设我有一个方法 def f(s:String *) = s.foreach( x = println(x) ) 现在我有一个数组: val a = Array("1","2","3") 如何使用as参数的元素调用f? 编辑: 所以给定一个,我想做以下事情: f(a(0),a(1),a(2)) // f("1","3") 解决方法 有一个操作符: f(a: _*
假设我有一个方法

def f(s:String *) = s.foreach( x => println(x) )

现在我有一个数组:

val a = Array("1","2","3")

如何使用as参数的元素调用f?

编辑:

所以给定一个,我想做以下事情:

f(a(0),a(1),a(2))  // f("1","3")

解决方法

有一个操作符:

f(a: _*)

该操作在章节4.6.2重复参数The Scala Language Specification Version 2.9中定义,并在6.6功能应用中进一步说明:

The last argument in an application may be marked as a sequence argument,e.g.
e : _*. Such an argument must correspond to a repeated parameter (§4.6.2) of type
S * […]. Furthermore,the type of e must conform to scala.Seq[T],for some type T which conforms to S. In this
case,the argument list is transformed by replacing the sequence e with its elements.

BTW你的f功能可以简化:

def f(s:String *) = s foreach println

或者更好(不鼓励等号,因为它表明该方法实际上返回了一些东西,但它“仅”返回Unit):

def f(s:String *) {s foreach println}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读