将强制数据传递给Kotlin中的超类 [英] Passing mandatory data to super classes in Kotlin

查看:166
本文介绍了将强制数据传递给Kotlin中的超类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Kotlin中创建实体时遇到问题.特别是,它是关于将数据传递给超类的.在下面找到一个示例.

I've got an issue creating entities in Kotlin. In particular, it's about passing data to a super class. Find an example below.

我有一个名为Trackable的抽象超类,该类可以扩展.它具有user属性,该属性存储谁创建了该特定对象.

I've got an abstract super class called Trackable that classes can extend. It has a user property that stores who has created that particular object.

abstract class Trackable(
  var createdBy: User
) : Persistable() 

名为Contract的类现在将实现Trackable父类,并且暂时存在编译时错误:

An class called Contract would now implement the Trackable super class with a compile-time error for the time being:

@Entity
data class Contract(
  var creationDate: LocalDateTime
) : Trackable() // compile error, no user passed here

因此,由于UserTrackable中的必填字段,因此我必须将User对象传递给Trackable构造函数.我首先想到的是创建一个称为creator的瞬态属性,然后将其传递给Trackable.

So, as the User is a mandatory field in Trackable, I have to pass a User object to the Trackable constructor. What came first into my mind was creating a transient property called creator that I pass on to the Trackable.

@Entity
data class Contract(
  @Transient val creator: User,
  var creationDate: LocalDateTime
) : Trackable(creator) 

但是,就域而言,这似乎是一个非常肮脏的解决方案,因为它污染了我的Contract.

However, domain-wise this seems to be a very dirty solution as it pollutes my Contract.

最近从Kotlin开始,我仍然缺乏适当和合理的模式来使用.有人可以帮我这个忙吗?

Having started with Kotlin recently I'm still lacking of appropriate and reasonable patterns to use. Could anyone please help me out with this?

推荐答案

数据类不能最好地用于继承,使用组合可能会更好,但是如果您真的想使用继承,那么恕我直言,这是最好的方法正在关注:

Data classes don't work best with inheritance, it might be better to use composition, but if you really want to use inheritance then IMHO best way to do it is following:

使用抽象字段声明抽象类:

Declare abstract class with abstract fields:

abstract class Trackable : Persistable(){
    abstract var createdBy: User

}

扩展抽象类并覆盖数据类中的属性:

Extend abstract class and override property inside data class:

data class Contract(
        override var createdBy: User,
        var creationDate: LocalDateTime) : Trackable()

这样可以避免拥有重复的属性,同时能够从parent类访问该属性,但实际上它是children的成员,从我的角度来看,这是最好的解决方案,因为您保留了data class的所有优点,但要随心所欲地服用盐粒.

This way you avoid having duplicate property while having ability to access that property from parent class but it is actually a member of children, from my perspective this is best solution as you keep all benefits of data class, but take it with grain of salt as it is subjective.

这篇关于将强制数据传递给Kotlin中的超类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆