Is there a more readable and and more robust (to refactoring) way to match on case classes like this ?
Very long case class with many "fields".
case class Data(name: String, time: Long, ..., userId: Option[UUID] ..., orders: Int, ... ) //more fields fields more
Works. But error prone when fields position changes. One ends up counting _
.
res match {
case data@Data(_,_,_,_,_,_,Some(id),_,_,_,6,_,_) => (id, data.orders)
case _ => ...
}
Works also. Is stable to changing orders. Gets really cumbersome with more checks in the guard. Also reading the value has to be repeated.
res match {
case data: Data if data.userId.isDefined && data.orders == 6 => (data.userId.get,data.orders)
case _ => ...
}
Is there a way to combine Variant A and B to get the benefit of both approaches ?
Starting Scala 3.7 named tuples make it possible
to match on a subset of case class fields by name. By doing so you no longer need to specify a long list of wildcard selectors for each field of a large case class.
so for example we can simplify
res match {
case data@Data(_,_,_,_,_,_,Some(id),_,_,_,6,_,_) => (id, data.orders)
}
to
res match
case Data(userId = Some(id), orders = myOrders) => (id, myOrders)