google-developer-training/android-basics-kotlin-unscramble-app

Android Basics: ViewModel - question about the content

diskostu opened this issue · 4 comments

URL of codelab
https://developer.android.com/codelabs/basic-android-kotlin-training-viewmodel

In which task and step of the codelab can this issue be found?
task 11 (Verify the ViewModel preserves data), right at the beginning of this task

Describe the problem
The docs say we need a backing property for the property currentWordCount and suggest the following code:

private var _currentWordCount = 0
val currentWordCount: Int
   get() = _currentWordCount

I don't really understand why such a backing property is needed. If the reason for it is to have a read only property accessible in other classes, why not use this code:

var currentWordCount = 0
   private set

Can you please explain why your code suggestion should be used? Why is it a better implementation? Thanks! 😊

@diskostu
Thank you for reaching out to us. In your way even though you make the setter private the variable is mutable. But it is always preferred in Kotlin to use immutable variables and to do that you need to make the variable which is accessed from outside immutable and add a backing filed:
https://kotlinlang.org/docs/properties.html#backing-fields
Happy coding!

I can understand that the field should not be modified from outside this class.
But, if the setter is private, the var field cannot be modified from outside the class. Or am I wrong?

@osuleymanova Also, I think you are mixing backing field and backing property in your comment. In this code:

private var _currentWordCount = 0
val currentWordCount: Int
   get() = _currentWordCount

the variable currentWordCount is a backing property, not a backing field.

@diskostu
Please refer to the following explanation:
Screen Shot 2022-05-12 at 9 17 47 AM