如何从类列表中仅获取确切的属性,例如
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)
如何从类列表中仅获取确切的属性,例如
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)
试试这个:
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)
你也可以做
for { person <- persons } yield person.name
这与地图基本相同的事情