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

ScalaMapVariadic Functions

Scala Problem Overview


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

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

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

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

Scala Solutions


Solution 1 - Scala

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

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

Solution 2 - Scala

Or this should work too:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondsgView Question on Stackoverflow
Solution 1 - ScaladsgView Answer on Stackoverflow
Solution 2 - ScalaAntonin BrettsnajdrView Answer on Stackoverflow