Reputation: 1193
I have a Scala case class with the following declaration:
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. Is there a way to pass this array to the Student
constructor? 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))
Upvotes: 2
Views: 948
Reputation: 44957
You can always write your own factory methods on the Student
companion object:
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. Something with automatic mappings to a database of some kind?
Upvotes: 5