0
假设我有一个具有多属性值的地图,我想选择一个特定的属性。对于元组的关键元素的Scala图,如何从元组中选择(项目?)特定项目?
例如,表示具有姓名,性别,年龄,说明的人员的表格的地图。
在SQL中,我会写“选择的人年龄其中名称=‘任何人’”
我怎么才能在斯卡拉这种效果?
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!
我喜欢这个答案,因为彼得给出了几种检索数据,但只是想讨论权衡。我认为我们应该总是做'persons.get(“Skyler White”)。map(_。age)'。如果不匹配,SQL不会返回任何行。所以,做人(“沃尔特怀特”)年龄是容易出错的。 “人们”(“沃尔特怀特”) - 2'更短但不可读。 – Rahul
太棒了!感谢Peter和Rahul。我不会想出如何避免抛出一个缺少密钥的异常。 –
@Rahul你是对的,我没有真正强调在我的答案中使用'Option'的重要性,所以谢谢! –