Scala比较case class并获取更改的字段

3

目前我使用scalaz和shapeless生成一个仅更新更改值的case类,但是为了实现一些扩展功能,我需要知道哪些字段(名称)发生了更改,有没有简单的方法可以做到?

或者一般情况下是否有更好的方法检查每个字段的相等性?

示例:

case class A(quanity: Option[Long], lose: Option[Long])

val a0 = A(Option(50), Option(10))
val a1 = A(Option(50), Option(20))

// Here it will be merged to a2 which is done by scalaz
// Now I need the fields that changed, ie. quanity or lose 
// (or any other field   if there are more
// a list or anything would be good enough:

val mergedList: List[String] = "lose" :: List()
1个回答

0
第一个想到的是 - productIterator:
    scala> A(5, "asd")
    res6: A = A(5,asd)

    scala> A(5, "asd")
    res7: A = A(5,asd)

    scala> A(1, "asd")
    res8: A = A(1,asd)

    scala> res6.productIterator.toList
    res9: List[Any] = List(5, asd)

    scala> res7.productIterator.toList
    res10: List[Any] = List(5, asd)

    scala> res8.productIterator.toList
    res11: List[Any] = List(1, asd)

    scala> res9 == res10
    res12: Boolean = true

    scala> res9 == res11
    res13: Boolean = false

    scala> res11.diff(res10)
    res18: List[Any] = List(1)

哦,我想我写错了我的问题,目前我需要案例类的命名字段,即case class A(quanity:Option [Long],x:Option [Long])。如果quanity更改,则需要“quanity”,如果x更改,则需要“x”。但是,我的案例类肯定更大,所以我认为有一种更简单的方法来做到这一点,而不是执行a.x == a.x或a.quanity = a.quanity。 - Christian Schmitt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接