Pattern match Scala case class capturing one field only

Viewed 374

I have a match statement against a case class with a large number of fields. Am I able to capture one of the fields by name and ignore the rest without specifying the other ones in position with underscores? This is particularly hard to do when what I want is deeply nested.

Here's what I have right now:

record match {
  case MyRecordType(_, _, _, MyNestedType(_, _, namedFieldAsVar, _), _, _, _) => 
    doStuffWith(namedFieldAsVar)

I would like to do something like this:

record match {
  case MyRecordType { nested = MyNestedType { namedFieldAsVar } } => 
    doStuffWith(namedFieldAsVar)
}

Other languages support this kind of pattern matching like this below (Rust), does Scala offer something similar?

match record {
  MyRecordType { named_field_as_var, .. } => do_stuff_with(named_field_as_var)
}
0 Answers
Related