scala:如何将扩展列表作为可变参数传递给方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5495428/
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 02:56:19  来源:igfitidea点击:

scala: How to pass an expanded list as varargs into a method?

scalamapvariadic-functions

提问by dsg

When creating a Mapin scala, I call Map(entities.map{e => e.id -> e}), and I get:

Map在 Scala 中创建 a时,我调用Map(entities.map{e => e.id -> e}),然后得到:

found   : scala.collection.mutable.IndexedSeq[(Int, Entity)]
required: (Int, Entity)

This is because the signature for Map.applyis: def apply[A, B](elems: (A, B)*): CC[A, B], which requires a varargs style argument.

这是因为签名Map.apply是: def apply[A, B](elems: (A, B)*): CC[A, B],它需要一个可变参数样式参数。

Is there a way to convert the IndexedSeqso that it can be accepted via Map.apply?

有没有办法转换IndexedSeq以便它可以通过接受Map.apply

回答by dsg

Try this: Map(entities.map{e => e.id -> e}:_*)

试试这个: Map(entities.map{e => e.id -> e}:_*)

Explicitly typing it as a varargs using :_*seems to work.

使用:_*似乎可以将其显式键入为可变参数。

回答by Antonin Brettsnajdr

Or this should work too:

或者这也应该有效:

entities.map{e => e.id -> e} toMap