[英]Pass array as separate arguments for case class
I have a Scala case class with the following declaration: 我有一个带有以下声明的Scala案例类:
case class Student(name: String, firstCourse: String, secondCourse: String, thirdCourse: String, fourthCourse: String, fifthCourse: String, sixthCourse: String, seventhCourse: String, eighthCourse: String)
Before I create a new Student
object, I have a variable holding the value for name
and an array holding the values for all 8 courses. 在创建新的
Student
对象之前,我有一个变量,该变量保存name
的值,一个数组保存所有8门课程的值。 Is there a way to pass this array to the Student
constructor? 有没有办法将此数组传递给
Student
构造函数? I want it to look cleaner than: 我希望它看起来比:
val firstStudent = Student(name, courses(0), courses(1), courses(2), courses(3), courses(4), courses(5), courses(6), courses(7))
You can always write your own factory methods on the Student
companion object: 您总是可以在
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))
}
}
and then just call it like this: 然后像这样调用它:
val courses: Array[String] = ...
val student = Student("Bob Foobar", courses)
Why you need a case class with 8 similar fields is another question. 为什么需要具有8个类似字段的案例类是另一个问题。 Something with automatic mappings to a database of some kind?
可以自动映射到某种数据库吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.