https://kotlinlang.org logo
Title
k

KronicDeth

12/18/2017, 3:30 PM
Can I turn this into a property with a
private set
and custom
get
?
java
  private ProjctSdksModel myModel
  public ProjectSdksModel getModel() {
    if (myModel == null) {
      myModel = new ProjectSdksModel();
      myModel.reset(null);
    }
    return myModel;
If I try
kotlin
var model: ProjectSdksModel? = null
        get() {
            if (this.model == null) {

            }

            return this.model
        }
        private set
I get warning that
this.model
is or
model
is recursive and my google-fu is failing for how to refer to the current property inside the getter
r

Ruckus

12/18/2017, 3:35 PM
Inside your getter, you need to replace
this.model
with
field
https://kotlinlang.org/docs/reference/properties.html#backing-fields
k

KronicDeth

12/18/2017, 3:35 PM
Thanks @Ruckus
👍 1
Is there something I should be doing different to avoid having to do
!!
immediately after initializing the
field
? I assume the mutability warning is for concurrency
get() {
            if (field == null) {
                field = ProjectSdksModel()
                field!!.reset(null)
            }

            return field
        }
Maybe I should go the "Backing Properties" route, because the getter is non-null even if the field is null
r

Ruckus

12/18/2017, 3:39 PM
You could always use something like
field = ProjectSdksModel().apply { reset(null) }
But in this case, backing properties are the way to go.
k

KronicDeth

12/18/2017, 3:41 PM
Is there a more compact way to handle the
null
reset back to
field
. It's not just a lateinit - there's other code that can reset the field to
null
r

Ruckus

12/18/2017, 3:43 PM
I don't know what
reset(null)
does, but a backing property should help separate the logic more cleanly.
u

umar

12/18/2017, 4:32 PM
You can use lateinit backing property