在 scala 中使用可变长度参数
我知道如何定义具有可变长度参数的方法:
case class taxonomy(vocabularies:(String,Set[String])*)
并且客户端代码非常干净:
val terms=taxonomy("topics"->Set("economic","politic")
,"tag"->Set("Libya","evolution")
)
但我想知道当我有一个像这样的变量(而不是变量序列)时如何使用这个案例类:
val notFormattedTerms = Map("topics"->Set("economic","politic")
,"tag"->Set("Libya","evolution"))
I know how to define a method with variable length argument:
case class taxonomy(vocabularies:(String,Set[String])*)
and client code is very clean:
val terms=taxonomy("topics"->Set("economic","politic")
,"tag"->Set("Libya","evolution")
)
but I want to Know how can I use this case class when I have a variable (instead of a Sequence of variable) like this:
val notFormattedTerms = Map("topics"->Set("economic","politic")
,"tag"->Set("Libya","evolution"))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
: _*
您实际上可以转换序列参数,使其看起来好像多个参数已传递给可变长度方法。然而,这种转换仅适用于(有序?)简单序列类型,并且在本例中不适用于Map
。因此,之前必须使用显式的toSeq
。With
: _*
you virtually transform a sequence argument so that it looks as if a several arguments had been passed to the variable length method. This transformation, however, only works for (ordered?) simple sequence types and, as in this case, not for aMap
. Therefore, one will have to use an explicittoSeq
before.