将数组作为case类的单独参数传递

时间:2018-02-23 21:54:27

标签: scala coding-style

我有一个带有以下声明的Scala案例类:

case class Student(name: String, firstCourse: String, secondCourse: String, thirdCourse: String, fourthCourse: String, fifthCourse: String, sixthCourse: String, seventhCourse: String, eighthCourse: String)

在我创建一个新的Student对象之前,我有一个变量保存name的值和一个包含所有8个课程值的数组。有没有办法将此数组传递给Student构造函数?我希望它看起来更清晰:

val firstStudent = Student(name, courses(0), courses(1), courses(2), courses(3), courses(4), courses(5), courses(6), courses(7))

1 个答案:

答案 0 :(得分:3)

您始终可以在Student随播广告对象上编写自己的工厂方法:

case class Student(
  name: String, firstCourse: String, secondCourse: String,
  thirdCourse: String, fourthCourse: String, 
  fifthCourse: String, sixthCourse: String, 
  seventhCourse: String, eighthCourse: String
)

object Student {
  def apply(name: String, cs: Array[String]): Student = {
    Student(name, cs(0), cs(1), cs(2), cs(3), cs(4), cs(5), cs(6), cs(7))
  }
}

然后就这样称呼它:

val courses: Array[String] = ...
val student = Student("Bob Foobar", courses)

为什么你需要一个包含8个类似字段的案例类是另一个问题。某种自动映射到某种数据库的东西?