1
votes

I am trying to implement non-nullable getter with nullable setter and nullable field.

  1. Field parent can be null, which means that the parent is this. If parent is not null, the parent is the parent value.
  2. Getter is not-nullable as it either returns this or parent
  3. 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.

1
I don't know what ORM you're using but chances are it's extending/implementing this abstract class/interface, so parent will be just another property. You better make parent an extension property if you want to supply any custom logic. - Eugen Pechanec

1 Answers

6
votes

At this time it's not possible to define a property with different getter and setter types. There is an open feature request for this functionality, but it's not planned for any specific Kotlin version.