0

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)
)
1
  • 1
    What do the maps look like? Commented Jan 28, 2014 at 21:30

2 Answers 2

3

Based on your edit you can do:

packages.map(p => Map(("name", p.name), ("description", p.description), ("homepage", p.homepage)))
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.