gpt4 book ai didi

scala - 将案例类字段与scala中另一个案例类的子字段进行比较

转载 作者:行者123 更新时间:2023-12-04 18:18:47 24 4
gpt4 key购买 nike

我有以下 3 个案例类:

case class Profile(name: String,
age: Int,
bankInfoData: BankInfoData,
userUpdatedFields: Option[UserUpdatedFields])

case class BankInfoData(accountNumber: Int,
bankAddress: String,
bankNumber: Int,
contactPerson: String,
phoneNumber: Int,
accountType: AccountType)

case class UserUpdatedFields(contactPerson: String,
phoneNumber: Int,
accountType: AccountType)

这只是枚举,但我还是添加了:
sealed trait AccountType extends EnumEntry

object AccountType extends Enum[AccountType] {
val values: IndexedSeq[AccountType] = findValues

case object Personal extends AccountType

case object Business extends AccountType

}

我的任务是——我需要写一个funcc Profile并将 UserUpdatedFields(所有字段)与 BankInfoData 中的一些字段进行比较...此函数用于查找哪些字段已更新。

所以我写了这个函数:
def findDiff(profile: Profile): Seq[String] = {
var listOfFieldsThatChanged: List[String] = List.empty
if (profile.bankInfoData.contactPerson != profile.userUpdatedFields.get.contactPerson){
listOfFieldsThatChanged = listOfFieldsThatChanged :+ "contactPerson"
}
if (profile.bankInfoData.phoneNumber != profile.userUpdatedFields.get.phoneNumber) {
listOfFieldsThatChanged = listOfFieldsThatChanged :+ "phoneNumber"
}
if (profile.bankInfoData.accountType != profile.userUpdatedFields.get.accountType) {
listOfFieldsThatChanged = listOfFieldsThatChanged :+ "accountType"
}
listOfFieldsThatChanged
}

val profile =
Profile(
"nir",
34,
BankInfoData(1, "somewhere", 2, "john", 123, AccountType.Personal),
Some(UserUpdatedFields("lee", 321, AccountType.Personal))
)

findDiff(profile)

它有效,但想要更清洁的东西..有什么建议吗?

最佳答案

如果将案例类转换为映射是一种简单的方法,那将是一项非常容易实现的任务。不幸的是,案例类在 Scala 2.12 中还没有提供开箱即用的功能(正如马里奥所说,在 Scala 2.13 中很容易实现)。

有一个名为 shapeless 的库,它提供了一些通用的编程实用程序。例如,我们可以编写一个扩展函数 toMap使用 RecordToMap从无形:

object Mappable {
implicit class RichCaseClass[X](val x: X) extends AnyVal {
import shapeless._
import ops.record._

def toMap[L <: HList](
implicit gen: LabelledGeneric.Aux[X, L],
toMap: ToMap[L]
): Map[String, Any] =
toMap(gen.to(x)).map{
case (k: Symbol, v) => k.name -> v
}
}
}

然后我们可以将它用于 findDiff :
def findDiff(profile: Profile): Seq[String] = {
import Mappable._

profile match {
case Profile(_, _, bankInfo, Some(userUpdatedFields)) =>
val bankInfoMap = bankInfo.toMap
userUpdatedFields.toMap.toList.flatMap{
case (k, v) if bankInfoMap.get(k).exists(_ != v) => Some(k)
case _ => None
}
case _ => Seq()
}
}

关于scala - 将案例类字段与scala中另一个案例类的子字段进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56099428/

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