斯卡拉:如何建模一个基本的父子关系(scala: how to model a basic pare

2019-07-29 02:53发布

我有一个具有多个产品品牌类

并在产品类我想拥有的品牌,这样的引用:

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

case class Product(val name: String, val brand: Brand)

我怎样才能poulate这些类???

我的意思是,我不能创造一个产品,除非我有一个品牌

除非我的产品列表我不能创造品牌(因为Brand.products是VAL)

什么是对这种关系进行建模的最好方法?

Answer 1:

我会问你为什么要重复的信息,说该产品是指其品牌在这两个列表,并为每个产品中。

不过,你可以这样做:

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)))

通过名字似乎PARAMS没有被允许的情况下不幸类。

另见本类似的问题: 实例化不可变对象配对



Answer 2:

由于您的问题是关于模型的这种关系,我会说为什么不只是他们模拟像我们在数据库中呢? 分离的实体和关系。

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


文章来源: scala: how to model a basic parent-child relation