Access parent case class from child using Monocle lens

127 Views Asked by At

I want to use optics in Scala to not go down a nested structure but rather traverse the other way around like going to Parent from Child.

case class Parent(param1: Int)
class Child(param2: Int)

val parent = Parent(param1)
val child = Child(param2)

// I would like something of this sort.
val parentParam1 = Lens[Child, Parent](_.parent)

I have tried creating a trait WithParent[T] that the child class extends. For example -

trait WithParent[T] extends scala.AnyRef with scala.Product {
  var parent: T = ???
}

case class Parent(param1: Int)
case class Child(param2: Int) extends WithParent[Parent]


object WithParentCheck extends App {
  val a = Parent(1)
  val b = Child(2)
  
  val parentParam1 = Lens[Child, Parent](_.parent)
}

I have 2 questions -

  1. Will this method work? If so can I define parent in the trait itself?
  2. Is there a better approach to this question?

Edit:

Edit 2: Account has an unique customer identifier.

Real World Scenario

case class Customer(id: String, account: Account)
case class Account(id: String, balance: Double, customerId: String)

val account = Account('01', 100, '1')
val cust = Customer('1', account)

// Accessing customer from account
val customerToAccount = Lens[Customer, Account](_.account)

My question: Is the reverse possible? Accessing customer from the account object?

Logic for my approach: trait MyParent[T] would contain a object/variable parent of type T which would be accessible from the case class extending it.

Thanks!

0

There are 0 best solutions below