scala – 是否可以更新实现共同特征的任何案例类的字段
发布时间:2020-12-16 18:52:12 所属栏目:安全 来源:网络整理
导读:让我们假设我们有一个共同的特质模型. trait Model { def id: String def updated: Date} 我们有2个案例类来扩展这个特性. case class C1(id: String,updated: Date,foo: String) extends Modelcase class C2(id: String,bar: Int) extends Model 是否可以编
让我们假设我们有一个共同的特质模型.
trait Model { def id: String def updated: Date } 我们有2个案例类来扩展这个特性. case class C1(id: String,updated: Date,foo: String) extends Model case class C2(id: String,bar: Int) extends Model 是否可以编写如下所示的实用程序函数,该函数将Model作为参数并返回带有更新字段的更新值的副本? object Model { def update[T <: Model](model: T): T = { model.copy(updated = new Date) // This code does not compile. } } 解决方法
你可以在这里写的“最佳”抽象是一个镜头看起来像:
trait Lens[A,B]{ def get: A => B def set: (A,B) => A } 这样你的代码看起来像: def update[A](that: A,value: Date)(implicit tLens: Lens[A,Date]): A = tLens set (that,value) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读