Kotlin: workaround for no lateinit when using custom setter?

Viewed 5885

In my activity I have a field that should be non-nullable and has a custom setter. I want to initialize the field in my onCreate method so I added lateinit to my variable declaration. But, apparently you cannot do that (at the moment): https://discuss.kotlinlang.org/t/lateinit-modifier-is-not-allowed-on-custom-setter/1999.

These are the workarounds I can see:

  • Do it the Java way. Make the field nullable and initialize it with null. I don't want to do that.
  • Initialize the field with a "default instance" of the type. That's what I currently do. But that would be too expensive for some types.

Can someone recommend a better way (that does not involve removing the custom setter)?

3 Answers

Replace it with a property backed by nullable property:

private var _tmp: String? = null
var tmp: String
    get() = _tmp!!
    set(value) {_tmp=value; println("tmp set to $value")}

Or this way, if you want it to be consistent with lateinit semantics:

private var _tmp: String? = null
var tmp: String
    get() = _tmp ?: throw UninitializedPropertyAccessException("\"tmp\" was queried before being initialized")
    set(value) {_tmp=value; println("tmp set to $value")}

I realized that you can also make your private property lateinit instead of making it nullable:

var tmp: T
    get() = _tmp
    set(value) {
        _tmp = value
        println("tmp set to $value")
    }

private lateinit var _tmp: T
Related