How do I map a sequence of objects to Maps in Scala?

How do I map a sequence of class instances to a sequence of Maps in Scala?

Assume that the instances are of the following type:

class Package(_name: String, _description: String, _homepage: String = null) {
  var name: String = _name
  var description: String = _description
  var homepage: String = _homepage
}

And we have a sequence of instances of this type:

var packages = Seq(
  new Package("A", "Package A", "https://github.com/package/a"),
  new Package("B", "Package B")
)

How do I map packages to a sequence of Maps?

The Maps should be equivalent to the following:

Seq(
  ("name" -> "A", "description" -> "Package A", "homepage" -> "https://github.com/package/a"),
  ("name" -> "B", "description" -> "Package B", "homepage" -> null)
)

Answers


Based on your edit you can do:

packages.map(p => Map(("name", p.name), ("description", p.description), ("homepage", p.homepage)))

To create a map of packages with name as the key and Package as the value this would do.

scala> packages.map(p => p.name -> p).toMap
res7: scala.collection.immutable.Map[String,Package] = Map(A -> Package@c3cec2e, B -> Package@73b5c648)

Need Your Help

Button removal in Corona

lua corona

I'm trying to nest pages and such with button presses in an app I am working on. However, as a widget, it carries over and such and must be removed using display.remove() or :removeSelf. I'm tryin...