2

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))

1 Answer 1

5

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.