Reputation: 2275
The Code A is from the artical LiveData with SnackBar, Navigation and other events (the SingleLiveEvent case).
navigateToDetails
is val variable, so I think that Code B can do the same work, is it right?
Code A
class ListViewModel : ViewModel {
private val _navigateToDetails = MutableLiveData<Event<String>>()
val navigateToDetails : LiveData<Event<String>> get() = _navigateToDetails
fun userClicksOnButton(itemId: String) {
_navigateToDetails.value = Event(itemId) // Trigger the event by setting a new Event as a new value
}
}
Code B
class ListViewModel : ViewModel {
private val _navigateToDetails = MutableLiveData<Event<String>>()
val navigateToDetails : LiveData<Event<String>> = _navigateToDetails
fun userClicksOnButton(itemId: String) {
_navigateToDetails.value = Event(itemId) // Trigger the event by setting a new Event as a new value
}
}
Upvotes: 1
Views: 362
Reputation: 170805
The point of get()
there is minor but it exists; code B stores the same reference in two fields and so uses a bit more memory for each instance of this class. Of course in this case there are probably few instances of ListViewModel
so it's unlikely to matter in practice.
Upvotes: 1
Reputation: 93759
Yes, there is no need for get()
here.
Adding get()
causes the expression after the =
to be re-evaluated every time the property is accessed. In this case, it's just pointing at a read-only property, so it will evaluate the same way every time anyway. If the expression pointed at a mutable property, or perhaps was a when
statement that is based on some mutable property, you might want to use the explicit getter so the underlying value changes when the state of the object changes. Conversely, if you only wanted the expression to be evaluated one time during initialization and thereafter always return the same value no matter what, you would not want to define a getter.
Note that get() =
is shorthand for get() { /* ... */ }
, similar to the shorthand you can use when writing single-expression functions. get()
means you are defining a getter function for the property. A bare =
means you are assigning a value to the backing field during initialization.
Upvotes: 3