如何使用scala中的烟囱将一个嵌套案例类转换为另一个嵌套案例,该嵌套案例在嵌套类中具有一个额外的字段

问题描述 投票:0回答:1

package a

final case class mySettings(multicache: myCacheSetting, defaultTtlHours: Duration)

final case class myCacheSetting(
    weightedRoundrobin: InternalWRRMultiCacheSetting,
    attempts: Int,
    clusters: Seq[MyClusterSetting]
)

final case class MyClusterSetting(id: String, settings: InternalMyClientSettings)

final case class InternalMyClientSettings(
    user: String,
    environment: Option[InternalMyClientEnvironmentSettings]
)

final case class InternalMyClientEnvironmentSettings(
    socketTimeout: Option[FiniteDuration],
    connectTimeout: Option[FiniteDuration],
)
final case class InternalWRRMultiCacheSetting(maxWeight: Int, incrementWeight: Int, decrementWeight: Int)

这个类需要转换成

package b

final case class mySettings(multicache: myCacheSetting, defaultTtlHours: Duration)

final case class myCacheSetting(
    weightedRoundrobin: InternalWRRMultiCacheSetting,
    attempts: Int,
    clusters: Seq[MyClusterSetting]
)

final case class MyClusterSetting(id: String, settings: InternalMyClientSettings)

final case class InternalMyClientSettings(
    user: String,
    company: String,
    environment: Option[InternalMyClientEnvironmentSettings]
)

final case class InternalMyClientEnvironmentSettings(
    socketTimeout: Option[FiniteDuration],
    connectTimeout: Option[FiniteDuration],
)
final case class InternalWRRMultiCacheSetting(maxWeight: Int, incrementWeight: Int, decrementWeight: Int)

如您所见,这两个类几乎相似,只是第二个类包含一个附加字段

company
company
需要用常量填充。

如果能解释一下您如何找到解决方案,我们将不胜感激

我尝试使用 scalaland:chimney 中的 into 和transformInfo,但没有帮助。 缺失的字段在转换时导致了很多问题

scala generics dto shapeless hlist
1个回答
0
投票

花了一些时间,但最新版本的 Chimney (

1.0.0-RC1
) 可以解决这个问题:

Transformer.define[a.mySettings, b.mySettings]
  .withFieldConst(_.multicache.clusters.everyItem.settings.company, "???")
  .buildTransformer

0.8.0 引入了嵌套路径,因此像

_.foo.bar.baz
这样的事情成为可能。然后 1.0.0-M5 将其扩展到
_.matching[Subtype]
(用于密封/枚举)、
_.everyItem
Iterable
s)、
_.everyMapKey
_.everyMapValue
Map
s),使得像
_.multicache.clusters.everyItem.settings.company
这样的规定成为可能.

© www.soinside.com 2019 - 2024. All rights reserved.