Chanaka Perera
Chanaka Perera

Reputation: 19

How would I alter a list within a list in Scala using functional programming

Imagine I have a list[list[object]] and I wanted to get a list[list[object.field]]

How would i be able to do this through functional programming

as in if val list = list[list[object]] i tried

val newList = list(_)(_1.map(object.field))

but this gave me an error and I am confused

I just started functional programming and scala so there might be something completely illogical with this statement

Upvotes: 0

Views: 43

Answers (1)

Ivan Stanislavciuc
Ivan Stanislavciuc

Reputation: 7275

You need to use map as following

  case class Obj(field: String)
  val list = List[List[Obj]]()

  val fields: List[List[String]] = list.map(_.map(_.field))

or same as

  val fields: List[List[String]] = list.map(innerList => innerList.map(obj => obj.field))

or if you want to have a flattened list of fields

  val fields: List[String] = list.flatMap(_.map(_.field))

Upvotes: 5

Related Questions