Scala: how to model a basic parent-child relationship

I have a Brand class that has several products.

And in the product class I want to have a brand link, for example:

case class Brand(val name:String, val products: List[Product]) case class Product(val name: String, val brand: Brand) 

How can I poulate these classes ???

I mean, I canโ€™t create a product if I donโ€™t have a brand

And I canโ€™t create a brand if I donโ€™t have a list of products (because Brand.products is val)

What would be the best way to model this relationship?

+6
source share
2 answers

I would question why you repeat the information, saying which products belong to that brand both in the list and in each product.

However, you can do this:

 class Brand(val name: String, ps: => List[Product]) { lazy val products = ps override def toString = "Brand("+name+", "+products+")" } class Product(val name: String, b: => Brand) { lazy val brand = b override def toString = "Product("+name+", "+brand.name+")" } lazy val p1: Product = new Product("fish", birdseye) lazy val p2: Product = new Product("peas", birdseye) lazy val birdseye = new Brand("BirdsEye", List(p1, p2)) println(birdseye) //Brand(BirdsEye, List(Product(fish, BirdsEye), Product(peas, BirdsEye))) 

The by-name parameter is apparently not allowed for case classes.

See also this similar question: Running immutable paired objects

+6
source

Since your question is about the model for these relationships, I will say, why not just model them, like what we do in the database? Separate the object and the relationship.

 val productsOfBrand: Map[Brand, List[Product]] = { // Initial your brand to products mapping here, using var // or mutable map to construct the relation is fine, since // it is limit to this scope, and transparent to the outside // world } case class Brand(val name:String){ def products = productsOfBrand.get(this).getOrElse(Nil) } case class Product(val name: String, val brand: Brand) // If you really need that brand reference 
+3
source

Source: https://habr.com/ru/post/913810/


All Articles