https://kotlinlang.org logo
Title
v

Vishnu Haridas

11/04/2019, 10:05 AM
Which is better, a
val
with a backing property, or a public property with a private setter? Is there any difference? For example,
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

hallvard

11/04/2019, 10:11 AM
Did you check with javap?
✔️ 1
v

Vishnu Haridas

11/04/2019, 10:19 AM
I did a decompile from Kotlin Bytecode to Java in Android Studio. Both (1) and (2) are same.
h

hallvard

11/04/2019, 10:21 AM
🙂
v

Vishnu Haridas

11/04/2019, 10:23 AM
Just checking if there is any preference for one style over the other? 🤔
s

Stephan Schroeder

11/04/2019, 10:28 AM
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

Burkhard

11/04/2019, 10:32 AM
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