如何在Scala中优雅地编写此函数?

时间:2014-01-05 21:40:21

标签: scala

假设我有以下类:

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:InfonewType:Type,那么

info.type.name == newType.name

现在我需要创建一个newInfo:Info给定info: InfonewType: 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
   ... // ???
}

1 个答案:

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