I am trying to implement non-nullable getter with nullable setter and nullable field.
- Field
parentcan be null, which means that the parent isthis. If parent is not null, the parent is theparentvalue. - Getter is not-nullable as it either returns
thisorparent - Setter can set nullable value as it can remove the current parent.
I tried this:
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "parent_id")
var _parent: T? = null
var parent: T
get() = if (isParent) this as T else _parent!!
set(value) {
_parent = if (value == null) null else value.parent
}
I don't like the _parent variable, but also it doesn't help with the setter, because it is still not-nullable as the parent: T, so the solution does not work.
parentwill be just another property. You better makeparentan extension property if you want to supply any custom logic. - Eugen Pechanec