对于元组键的Scala映射,如何从元组中选择(项目?)特定项?

时间:2015-09-25 15:28:39

标签: scala hashmap

假设我有一个包含多属性值的地图,我想要选择一个特定的属性。

例如,一张地图,代表一个人名表,性别,年龄,描述。

在SQL中,我会写“从名为='whomever'的人中选择年龄”

我如何在Scala中获得该效果?

val people = Map(
 "Walter White" -> ("male",52,"bad boy"),
 "Skyler White" -> ("female",42,"morally challenged mom")
 )

// equivalent of select * from people. This works.
for ((name,(gender,age,desc)) <- people) println(s"$name is a $age year old $gender and is a $desc")

// what should be the syntax to get "the age of Walter White is 52"?
// in SQL, it would be "'The age of Walter White is ' || (select age from people where name='Walter White')"
// what would it be in Scala?
println("The age of Walter White is " + people("Walter White")(1)) // not this!

1 个答案:

答案 0 :(得分:2)

您可以创建一个Person案例类,并使用Person而不是元组创建新地图。

case class Person(name: String, gender: String, age: Int, description: String)

val persons = people map { case (name, (gender, age, descr)) =>
  name -> Person(name, gender, age, descr)
}

这样你可以写:

persons("Walter White").age              // Int = 52
persons.get("Skyler White").map(_.age)   // Option[Int] = Some(42)

您还可以使用原始代码访问年龄:

people("Walter White")._2                // Int = 52