Vasiliy Galkin Vasiliy Galkin - 11 months ago 83
Scala Question

Can I return Map collection in Scala using for-yield syntax?

I'm fairly new to Scala, so hopefully you tolerate this question in the case you find it noobish :)

I wrote a function that returns a Seq of elements using yield syntax:

def calculateSomeMetrics(names: Seq[String]): Seq[Long] = {
for (name <- names) yield {
// some auxiliary actions
val metrics = somehowCalculateMetrics()
metrics
}
}


Now I need to modify it to return a Map to preserve the original names against each of the calculated values:

def calculateSomeMetrics(names: Seq[String]): Map[String, Long] = { ... }


I've attempted to use the same yield-syntax but to yield a tuple instead of a single element:

def calculateSomeMetrics(names: Seq[String]): Map[String, Long] = {
for (name <- names) yield {
// Everything is the same as before
(name, metrics)
}
}


However, the compiler interprets it
Seq[(String, Long)]
, as per the compiler error message

type mismatch;
found : Seq[(String, Long)]
required: Map[String, Long]


So I'm wondering, what is the "canonical Scala way" to implement such a thing?

Answer Source

Either:

def calculateSomeMetrics(names: Seq[String]): Map[String, Long] = {
  (for (name <- names) yield {
    // Everything is the same as before
    (name, metrics)
  }).toMap
}

Or:

names.map { name =>
  // doStuff
  (name, metrics)
}.toMap
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download