Which is better, a `val` with a backing property, ...
# announcements
v
Which is better, a
val
with a backing property, or a public property with a private setter? Is there any difference? For example,
Copy code
class Foo {

    // (1) - public property with a private setter
    var isSyncing = false
        private set
    
    // (2) - val with a backing property
    private var isSyncing_ = false
    val isSyncing get() = isSyncing_
}
1
h
Did you check with javap?
✔️ 1
v
I did a decompile from Kotlin Bytecode to Java in Android Studio. Both (1) and (2) are same.
h
🙂
v
Just checking if there is any preference for one style over the other? 🤔
s
hmm, i always did (2) but (1) is probabaly nicer in that it communicates that the value you get isn’t immutable.
(2) is more efficient though, because a private property is actually converted to a Java field. So it can be accessed from within the class without going through getters and setters.
b
That is only really true for android without any of the optimizations of the jvm. final getters within the same class should just be optimized to a field access.
I personally prefer (1). It is less work to write and it shows a clearer intend. The advantage of (2) is that the backing field can have a different type eg. public get
List
and private
MutableList
👍 6
✔️ 2