Search code examples
javakotlinidioms

Idiomatic Kotlin when checking null


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


Solution

  • 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");
    }