如何从类列表中仅获取确切的属性,例如
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)
答案 0 :(得分: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)
答案 1 :(得分:0)
for { person <- persons } yield person.name
这与地图基本相同