https://kotlinlang.org logo
#android
Title
# android
v

voben

11/05/2019, 6:31 PM
What’s the difference between creating a property with a getter function vs one without. Are these 2 actually the same thing?
Copy code
val myLiveData: LiveData<String> = _backingLiveData

val myLiveData2: LiveData<String> 
      get() = _backingLiveData
c

Casey Brooks

11/05/2019, 6:33 PM
The first one caches the value in a backing field, and is executed once at object creation. The second one does not have a backing field, is lazily evaluated, and gets executed on each access
👍 1
✔️ 5
🙏 1
Here’s a playground demonstrating that behavior https://pl.kotl.in/hJgjq9XSh
j

John

11/05/2019, 9:43 PM
The second one would be the same as
Copy code
fun getMyLiveData(): LiveData<String> { 
   return _backingLiveData
}
a

arekolek

11/05/2019, 11:29 PM
The first one caches the value in a backing field, and is executed once at object creation. The second one does not have a backing field, is lazily evaluated, and gets executed on each access
That’s not a good way of looking at it. It makes it sound like the first one is better, while it’s not. See https://kotlinlang.org/docs/reference/properties.html#backing-properties Here’s the decompiled bytecode for that example:
Copy code
private final MutableLiveData<String> _backingLiveData = new MutableLiveData<>();

private final LiveData<String> myLiveData = _backingLiveData;

public final LiveData<String> getMyLiveData() {
  return myLiveData;
}

public final LiveData<String> getMyLiveData2() {
  return _backingLiveData;
}
You can see that
myLiveData
uses more memory, but doesn’t have any performance benefit.
1
👍 1
n

nrobi

11/06/2019, 9:04 AM
If you use
proguard/R8
, the first option may be still optimized
👍 1
3 Views