1

如何从类列表中仅获取确切的属性,例如

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

val a = Person("a", 1)
val b = Person("b", 1)
val persons = List(a, b)

val names = ???

assertEquals(List("a", "b"), names)
4

2 回答 2

3

试试这个:

scala> val names = persons.map(_.name)
names: List[String] = List(a, b)

或者,如果您想同时访问多个字段:

scala> val names = persons.map{ case Person(name, age) => name }
names: List[String] = List(a, b)
于 2012-04-17T16:16:03.960 回答
0

你也可以做 for { person <- persons } yield person.name 这与地图基本相同的事情

于 2012-04-17T21:14:25.420 回答