JakoSA12
JakoSA12

Reputation: 13

Scala - how to filter fields from nested classes?

I'm having a class that has nested classes inside of it:

object Notes{

case class Notes(node_number: String,
                  name: String,
                  url: String,
                  Datafiles: List[Data])

case class Data(code: Option[String],
                Datafilename: Option[String])
                DataDate: Option[String])

I'm trying to basically filter datafiles based on the datafilename. Meaning, I would like to retrieve the list of all data files, and then filter them based on them ending with .txt.

What I tried:

def m1(input: List[Notes]): (Int) = {
    val x =  input.map(x => x.Datafiles)
    val xy = x.filter(_.Datafilename.get.endsWith(".txt")))
} 

No matter what I try, I unfortunately can't do so. I've tried double filtering but that doesn't let me select Datafilename and I'm getting different issues with filtering.

Any suggestions would be great.

Upvotes: 1

Views: 204

Answers (3)

Using standard notation this alternative is safe and efficient.

final case class Notes(
    nodeNumber: String,
    name: String,
    url: String,
    dataFiles: List[Data]
)

final case class Data(
    code: Option[String],
    dataFilename: Option[String],
    dataDate: Option[String]
)

def m1(input: List[Notes]): Int =
  input
    .iterator
    .flatMap(_.dataFiles)
    .flatMap(_.dataFilename)
    .count(_.endsWith(".csv"))

Upvotes: 2

Brian McCutchon
Brian McCutchon

Reputation: 8584

Instead of map, use flatMap, then use count to get the count at the end:

def m1(input: List[Notes]): Int =
  input.flatMap(_.Datafiles)
    .count(_.Datafilename.exists(_.endsWith(".txt")))

Upvotes: 3

alhuelamo
alhuelamo

Reputation: 135

Using get on an Option can be dangerous since it will crash if it is None. A more concise solution that also utilizes Option combinators could be:

def m1(input: List[Notes]): Int =
  input.flatMap(_.Datafiles)
    .filter(_.Datafilename.map(_.endsWith(".txt")).getOrElse(false))
    .length

Upvotes: 1

Related Questions