Idiomatic Kotlin when checking null

Héctor :

In Java, I would do something like this:

class Person {

    private Record record;

    public String name() {
      record().get("name");
    }

    private Record record() {
      if (record == null) {
        refetch();
      }
      return record;
    }

    private void refetch() {
      record = service.doSomething()
    }

}

In Kotlin, I have this equivalent code:

class Person(private var record: Record?) {

    fun name() : String {
      record().get("name");
    }

    private fun record() : Record {
      record ?: refetch()
      return record!!;
    }

    private fun refetch() {
      record = service.doSomething()
    }

}

As you see, I'm using !! operator, and I don't really like. Is there another more idiomatic way to do this?

If I simply follow the Java way (if (record == null)), I get this error:

Smart cast to "Record" is impossible, because "record" is a mutable property that could have been changed by this time

JB Nizet :

In idiomatic Kotlin, you would use a lazy delegated property:

class Person(private val service: Service) {

    private val record by lazy { service.doSomething() }

    fun name() = record.get("name");
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=90161&siteId=1
Recommended