Scala - 具有大量字段的域对象

时间:2018-02-18 20:02:08

标签: scala apache-spark dao dto

这可能是一个愚蠢的问题,但我对Scala相对较新,所以请耐心等待。我正在尝试为Scala中的Spark作业建模域对象,它反映了源记录的数据结构并包含100多个字段。我试图找出建模的最佳方法,因为我觉得将所有字段添加到单个案例类中感觉不舒服。我想过将密切关联的字段分组到嵌套的case类中,但后来我在一些地方读到了不建议使用嵌套案例类。我希望得到一些关于什么是最好的方法的意见。

编辑:回应阿尔瓦罗的评论:

所以从本质上说,我们不建议这样做:

case class Product(name: String,
                   desc: String,
                   productGroup: String) {


  case class ProductPack(packType: String,
                         packQuantity: Int,
                         packQuantityUnit: String,
                         packUnitPrice: Float)
}

虽然这没关系:

case class Product(name: String,
                   desc: String,
                   productGroup: String,
                   productPack: ProductPack) {


}

case class ProductPack(packType: String,
                       packQuantity: Int,
                       packQuantityUnit: String,
                       packUnitPrice: Float) {

}

1 个答案:

答案 0 :(得分:2)

您的更新是正确的。

另一种选择:如果案例类在另一个概念的上下文中大多有意义,有时我会在概念的同伴中定义案例类:

public void TrySomething(int sec)
{
    var sw = Stopwatch.StartNew();
    while (true)
    {
        var result = ...
        // do useful stuff
        if (sw.Elapsed.TotalSeconds >= (double)sec)
        {
            return result;
        }
    }
}

那也应该没问题。该类包含在一个对象中,但它不是case class Product( name: String, desc: String, productGroup: String productPack: Product.Pack ) object Product { case class Pack( packType: String, packQuantity: Int, packQuantityUnit: String, packUnitPrice: Float ) } 类中的“嵌套”。