我正在使用 scala 3.3 构建一个
map
变量,用于临时存储学校信息,如下所示。
地图的变量:
"staff" -> Set[CreateStaff]
"students" -> Set[CreateStudent]
"books" -> Set[CreateBook]
地图将数据存储在异构
Set()
参数中。
数据是使用案例类
CreateStaff
、CreateStudent
和 CreateBook
- School
的特征生成的。
我尝试使用代码
mapOS("staff")+=newStaffA
将数据存储在上面的地图变量中,这会给出如下错误。
CreateStudent
和CreateBook
案例类也会出现相同的错误,我在错误文本中省略了它们。
错误:
error: type mismatch;
found: Map[String,scala.collection.mutable.Set[_ >: this.CreateBook with this.CreateStudent with this.CreateStaff <: Product with this.School with java.io.Serializable]] (in scala.collection.mutable)
required: Map[String,Set[this.School]] (in scala.collection.immutable)
val mapOS: Map[String, Set[School]] = mutable.Map("staff" -> mutable.Set[CreateStaff](), "students" -> mutable.Set[CreateStudent](), "books" -> mutable.Set[CreateBook]())
error: value += is not a member of Set[this.School]
Expression does not convert to assignment because receiver is not assignable.
mapOS("staff")+=newStaffA
... OMITTED SIMILAR ERRORS FOR CreateStudent and CreateBook case classes
...
我当前的代码如下所示。
你能帮我找出并修复错误吗!
预先感谢您的帮助!
学校.scala:
import scala.collection.immutable
import scala.collection.mutable
sealed trait School
final case class CreateStaff(id: String, name: String) extends School
final case class CreateStudent(id: String, name: String) extends School
final case class CreateBook(id: String, name: String) extends School
val mapOS: Map[String, Set[School]] = mutable.Map("staff" -> mutable.Set[CreateStaff](), "students" -> mutable.Set[CreateStudent](), "books" -> mutable.Set[CreateBook]())
val newStaffA: CreateStaff = CreateStaff("id1", "name1")
val newStaffB: CreateStaff = CreateStaff("id1", "name1")
val newStudentA: CreateStudent = CreateStudent("id1", "name1")
val newStudentB: CreateStudent = CreateStudent("id1", "name1")
val newBookA: CreateBook = CreateBook("id1", "name1")
val newBookB: CreateBook = CreateBook("id1", "name1")
mapOS("staff")+=newStaffA
mapOS("staff")+=newStaffB
mapOS("students")+=newStudentA
mapOS("students")+=newStudentB
mapOS("books")+=newBookA
mapOS("books")+=newBookB
println(mapOS.getOrElse("staff", Set.empty))
太建立在我关于拥有一个类而不是地图的评论之上,这里是一个示例,说明如果这样建模的话,它会是什么样子:
final case class CreateStaff(id: String, name: String)
final case class CreateStudent(id: String, name: String)
final case class CreateBook(id: String, name: String)
final case class School(
staff: Set[CreateStaff] = Set.empty[CreateStaff],
students: Set[CreateStudent] = Set.empty[CreateStudent],
books: Set[CreateBook] = Set.empty[CreateBook],
)
val school = School()
val staff = CreateStaff("id1", "name1")
val student = CreateStudent("id1", "name1")
val book = CreateBook("id1", "name1")
val updatedSchool = school.copy(
staff = school.staff + staff,
students = school.students + student,
books = school.books + book,
)
println(updatedSchool.staff) // prints "Set(CreateStaff(id1,name1))"
您可以在 Scastie 上使用此代码。
对我做出的决定的一些评论: