使用 Scala 的可变参数 [英] Using varargs from Scala

查看:37
本文介绍了使用 Scala 的可变参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力弄清楚如何执行以下操作:

I'm tearing my hair out trying to figure out how to do the following:

def foo(msf: String, o: Any, os: Any*) = {
    println( String.format(msf, o :: List(os:_*)) )
}

我必须分别用 oos Seq 声明方法是有原因的.基本上,我最终得到了使用单个对象参数(List 类型)调用的格式方法.正在尝试:

There's a reason why I have to declare the method with an o and an os Seq separately. Basically, I end up with the format method called with a single object parameter (of type List ). Attempting:

def foo(msf: String, o: Any, os: Any*) = {
    println( String.format(msf, (o :: List(os:_*))).toArray )
}

给我类型错误:

找到:数组[任何]

必需的序列[java.lang.Object]

required Seq[java.lang.Object]

我试过强制转换,它可以编译但由于与第一个示例几乎相同的原因而失败.当我尝试

I've tried casting, which compiles but fails for pretty much the same reason as the first example. When I try

println(String.format(msg, (o :: List(os:_*)) :_* ))

这无法编译隐式转换歧义(any2ArrowAssocany2stringadd)

this fails to compile with implicit conversion ambiguity (any2ArrowAssoc and any2stringadd)

推荐答案

def foo(msf: String, o: AnyRef, os: AnyRef*) = 
  println( String.format(msf, (o :: os.toList).toArray : _* ))

这篇关于使用 Scala 的可变参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆