将数组作为 case class 的单独参数传递
Pass array as separate arguments for case class
我有一个带有以下声明的 Scala 案例 class:
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))
您始终可以在 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 个相似字段的案例 class 是另一个问题。自动映射到某种数据库的东西?
我有一个带有以下声明的 Scala 案例 class:
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))
您始终可以在 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 个相似字段的案例 class 是另一个问题。自动映射到某种数据库的东西?