假设我有以下类:
case class Field(name: String, default: String)
case class Type(name: String, fields: Set[Field])
case class Info(name: String, type: Type, values: Map[Field, String])
显然对于任何info:Info
info.values.keySet == info.type.fields
假设我还有info:Info
和newType:Type
,那么
info.type.name == newType.name
现在我需要创建一个newInfo:Info
给定info: Info
和newType: Type
,以便:
1. newInfo.type == newType
2. newInfo.values.keySet = newType.fields
3. for each newField in newType.fields if !info.type.fields.contains(newField)
newInfo.values(newField) == newField.default
我想知道如何编写一个函数来简单而优雅地创建newInfo
:
def makeNewInfo(info: Info, newType: Type): Info = {
assert info.type.name == newType.name
... // ???
}
答案 0 :(得分:2)
val droppedFields = info.type.fields -- newType.fields
val addedFields = newType.fields -- info.type.fields
info.copy(values = info.values -- droppedFields ++ addedFields.map(f => (f, f.default))(collection.breakOut))