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

scala – 名称重复参数

发布时间:2020-12-16 19:07:27 所属栏目:安全 来源:网络整理
导读:如何在 Scala中传递名称重复的参数? 以下代码无法正常工作: scala def foo(s: (= String)*) = {console:1: error: no by-name parameter type allowed here def foo(s: (= String)*) = { ^ 有没有其他方法我可以传递一个可变数量的名称参数到方法? 解决方
如何在 Scala中传递名称重复的参数?

以下代码无法正常工作:

scala> def foo(s: (=> String)*) = {
<console>:1: error: no by-name parameter type allowed here
       def foo(s: (=> String)*) = {
                   ^

有没有其他方法我可以传递一个可变数量的名称参数到方法?

解决方法

这不是很漂亮,但它允许您传递byname参数varargs样式

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"))

这产生

在foo

在fooF1F2

(编辑:李大同)

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

    推荐文章
      热点阅读