A common knowledge question around using implicit ...
# android
b
A common knowledge question around using implicit getter/setter in kotlin. I am writing a boolean that would return true/false based on enum of a particular kind. Is an assignment preferred in this case or a get() method? I am familiar with using get() as it looks good and provides a clear definition of the variable. Please provide your comments on this. Below is the code snippet:
Copy code
val isFord: Boolean
    get() = carType == CarType.FORD
vs:
Copy code
val isFord = carType == CarType.FORD
e
the former is computed on every
get
, the latter is computed at assignment time and stored in a backing field
b
Is there any preference on what to use? As mentioned, I prefer using
get()
as that makes the definition clearer.
e
depends in general, they mean different things and have different advantages/disadvantages
in this case I'd use the former - there's no point in caching an enum
==
b
Thank You!!
l
You can also use
inline get() = carType == CarType.FORD
, so that this method virtually does not exist
2
k
@Luke Is there a difference between
inline get() = carType == CarType.FORD
and latter example? They are both computed once.
e
inline is just like the first example except inlined into the caller
l
1️⃣
Copy code
val isFord = carType == CarType.FORD
A variable is created in the class, is initialized to a boolean, and never changes afterward. 2️⃣
Copy code
val isFord: Boolean
    get() = carType == CarType.FORD
Basically. a method is created in the bytecode and called when the variable is used, and it returns the computation of
carType == CarType.FORD
. The result will vary with
carType
3️⃣
Copy code
val isFord: Boolean
    inline get() = carType == CarType.FORD
Whenever
isFord
is called, the compiler replaces
isFord
by the getter's body, in this case
carType == CarType.FORD
, so there is no method/variable added to the class in the bytecode
e
3️⃣ there actually is a method added in bytecode so that it's callable by reflection, but normal callers will inline a copy of the code
l
Hun, the more you know. Thanks for the clarification
k
@ephemient Is this method in the bytecode static or it relocates memory each time it's been called?