1

How to get only exact attributes from list of classes, e.g.

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)

2 Answers 2

3

Try this:

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

Or this if you want access to more than one field at the same time:

scala> val names = persons.map{ case Person(name, age) => name }
names: List[String] = List(a, b)
2
  • Good, thanks, you also may add this val names = persons.map{ case p:Person => p.name } to your answer
    – yons88
    Apr 17, 2012 at 16:25
  • 2
    @yons88, case p:Person => p.name is just a more verbose way of writing _.name. The type annotation is unnecessary since Scala already knows it's operating on a List[Person], and p => p.name is just a more verbose version of _.name.
    – dhg
    Apr 17, 2012 at 16:27
0

you also can do for { person <- persons } yield person.name which is basically the same thing as the map

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.