问题描述
我有一个品牌类,其中有几种产品
I have a Brand class that has several products
在产品类别中,我想引用该品牌,例如:
And in the product class I want to have a reference to the brand, like this:
case class Brand(val name:String, val products: List[Product])
case class Product(val name: String, val brand: Brand)
我如何填写这些课程?
我的意思是,除非拥有品牌,否则我无法创建产品
I mean, I can't create a product unless I have a brand
除非拥有产品列表,否则我无法创建品牌(因为Brand.products是有效值)
And I can't create the brand unless I have a list of Products (because Brand.products is a val)
为这种关系建模的最佳方法是什么?
What would be the best way to model this kind of relation?
推荐答案
我会问您为什么要重复这些信息,方法是说列表和每种产品中哪些产品与哪个品牌相关.
I would question why you are repeating the information, by saying which products relate to which brand in both the List and in each Product.
仍然可以做到:
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)))
不幸的是,案例类似乎不允许使用按名称命名的参数.
By-name params don't seem to be allowed for case classes unfortunately.
另请参阅类似的问题:实例化不可变的配对对象
See also this similar question: Instantiating immutable paired objects
这篇关于Scala:如何为基本的父子关系建模的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!