Setter for optional property

I need an optional property, but I want the setter to forbid null.

var myProperty: Long?
    set(newValue) {
        if (newValue != null) {
            field = someMethod(newValue)
        }
    }

I think Kotlin should support something like this:

var myProperty: Long?
    set(newValue: Long) {
        field = someMethod(newValue)
    }

This looks vaguely like something lateinit handles. Agree or disagree?

Edit: I mean, clearly they’re different because you can only set a lateinit once, IIRC. But still, I imagine the use cases overlap somewhat.

@nanodeath
In some cases, they overlap. Sometimes they don’t. I still need the property to be optional, because it’s completely okay if it’s null. But once it’s set to value, it shouldn’t be set to null again. If the property had to have a value every time I access it, then I could use lateinit. In my case, I can’t.

You cannot assign an optional long type to null safe type just like var cannot be assigned to val. Also, if you have a optional property you can safely use it without worrying about NPE, thats what null safety is designed for. Would you not want to do something like this?

      var myProperty: Long? = Long.MIN_VALUE
        get() = myProperty
        set(newValue) {
            field = newValue?.toLong()
        }

This is covered by https://youtrack.jetbrains.com/issue/KT-4075, which will likely be implemented at some point.

1 Like

This is tracked only for setters of optional property. In Kotlin, we cannot assign a Long? to Long type. Correct?

I created the thread for optional properties, but it is actually about general concept. The issue linked by @yole is exactly what I meant.

In this case you can use elvis operator
set(value) { field = someMethod(value ?: return) }