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

B. *_*ith 2 coding-style scala

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

case class Student(name: String, firstCourse: String, secondCourse: String, thirdCourse: String, fourthCourse: String, fifthCourse: String, sixthCourse: String, seventhCourse: String, eighthCourse: String)
Run Code Online (Sandbox Code Playgroud)

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

val firstStudent = Student(name, courses(0), courses(1), courses(2), courses(3), courses(4), courses(5), courses(6), courses(7))
Run Code Online (Sandbox Code Playgroud)

And*_*kin 5

您始终可以在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))
  }
}
Run Code Online (Sandbox Code Playgroud)

然后就这样称呼它:

val courses: Array[String] = ...
val student = Student("Bob Foobar", courses)
Run Code Online (Sandbox Code Playgroud)

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