如何将一系列对象映射到Scala中的Maps?

时间:2014-01-28 21:29:18

标签: scala

如何将一系列类实例映射到Scala中的一系列地图?

假设实例属于以下类型:

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

我们有一系列此类实例:

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

如何将packages映射到一系列地图?

地图应与以下内容相同:

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

2 个答案:

答案 0 :(得分:3)

根据您的编辑,您可以执行以下操作:

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

答案 1 :(得分:1)

要创建packages的地图,其中name为关键字,Package为此值。

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