gpt4 book ai didi

scala - 将数组作为案例类的单独参数传递

转载 作者:行者123 更新时间:2023-12-02 20:30:21 24 4
gpt4 key购买 nike

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

case class Student(name: String, firstCourse: String, secondCourse: String, thirdCourse: String, fourthCourse: String, fifthCourse: String, sixthCourse: String, seventhCourse: String, eighthCourse: String)

在创建新的 Student 对象之前,我有一个保存 name 值的变量和一个保存所有 8 门类(class)的值的数组。有没有办法将此数组传递给 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 个相似字段的案例类是另一个问题。有自动映射到某种数据库的东西吗?

关于scala - 将数组作为案例类的单独参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48956760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com