Vojtěch
Vojtěch

Reputation: 12416

Nullable field with Non-nullable getter

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.

Upvotes: 1

Views: 2047

Answers (1)

yole
yole

Reputation: 97338

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.

Upvotes: 7

Related Questions