使用 Scala 的可变参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1008783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 01:27:49  来源:igfitidea点击:

Using varargs from Scala

scalavariadic-functions

提问by oxbow_lakes

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:_*)) )
}

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

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

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

Gives me the type error:

给我类型错误:

found: Array[Any]

required Seq[java.lang.Object]

找到:数组[任何]

必需的序列[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:_*)) :_* ))

this fails to compile with implicit conversion ambiguity (any2ArrowAssocand any2stringadd)

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

回答by James Iry

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

回答by Daniel C. Sobral

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

or

或者

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

I much prefer the latter, though it has no locale* support.

我更喜欢后者,尽管它没有语言环境* 支持。

  • Scala 2.8 does have locale support with RichString's format.
  • Scala 2.8 确实支持 RichString 格式的区域设置。