23

Consider the following ways to expose MutableLiveData:

Method A

class ThisViewModel : ViewModel() {

    private val _someData = MutableLiveData(true)
    val someData: LiveData<Boolean>
        get() = _someData
}

// Decompiled Kotlin bytecode

public final class ThisViewModelDecompiled extends ViewModel {

   private final MutableLiveData _someData = new MutableLiveData(true);

   @NotNull
   public final LiveData getSomeData() {
      return (LiveData)this._someData;
   }
}

Method B

class ThatViewModel : ViewModel() {

    private val _someData = MutableLiveData(true)
    val someData: LiveData<Boolean> = _someData
}

// Decompiled Kotlin bytecode

public final class ThatViewModelDecompiled extends ViewModel {

   private final MutableLiveData _someData = new MutableLiveData(true);

   @NotNull
   private final LiveData someData;

   @NotNull
   public final LiveData getSomeData() {
      return this.someData;
   }

   public ThatViewModel() {
      this.someData = (LiveData)this._someData;
   }
}

Is there a reason to use Method B over Method A?

2 Answers2

13

From the Java perspective, Method A has one less field in the class, thus is "more" efficient. From the Kotlin perspective, Method B denotes a bit more clearly, that the non-mutable property is a direct reference to the mutable one. Also Kotlin is clever enough to locally access the field rather than the getter method.

Is there a reason to use Method B over Method A?

In general is merely a matter of taste. Looking at it from a micro-optimization perspective it depends on whether or not you'd also use this reference within the class itself.

tynn
  • 38,113
  • 8
  • 108
  • 143
8

Starting from Kotlin 1.4-M2 you can do simply:

private val myMutableLiveData = MutableLiveData<String>()
val myLiveData : LiveData<String> by this::myMutableLiveData

The this:: is unfortunately needed, otherwise does not compile.

I found this in Igor Wojda's answer which discusses other approaches. Unfortunately his answer in this question was deleted.

Mister Smith
  • 27,417
  • 21
  • 110
  • 193
  • the link is not referring to the answer you mentioned, it's referring to Igor Wojda's profile. – Kaan Sep 15 '22 at 00:17