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

sudhanshu singh

05/17/2018, 11:05 AM
is there any difference in these two
Copy code
val isEmpty: Boolean
    get() = this.size == 0

val isEmpty =  this.size==0
l

lex

05/17/2018, 11:08 AM
yes, in first case it will be getter method with
this.size == 0
body, in second you just initialize property
🙏 1
j

julioyg

05/17/2018, 11:08 AM
you beat me to it
p

Paul Woitaschek

05/17/2018, 11:45 AM
Yep, when the size changes, the value returned from the second property won't get updated
l

louiscad

05/17/2018, 12:08 PM
In other words, the second one is an immutable property with a backing field that can't change while the first ont is a read only property that returns isEmpty according to the curreny value of size
a

adam-mcneilly

05/17/2018, 3:23 PM
In these cases - where you want to use the first one because you don't want the immutable property - is it better to use a function instead of a val/override get, or are they effectively the same?
I find myself using the first one a lot more because I like the style, and that's probably fine for all intents and purposes, right?
l

louiscad

05/17/2018, 3:32 PM
@adam-mcneilly Computed read-only properties are fine and idiomatic, in fact you can see a lot of them in the stdlib, especially in collections
1
👍 1