https://kotlinlang.org logo
#codereview
Title
# codereview
h

hisham bin awiad

10/31/2021, 1:16 PM
Hi guys .... hope you doing will what is the diff and what should i choose
Copy code
private val empID 
             get() = (userModelId ?: session.getUserModelId().toSafetyString()).toSafetyString()

	private val empID2 by lazy { (userModelId ?: session.getUserModelId().toSafetyString()).toSafetyString()  }
s

sbyrne

10/31/2021, 1:38 PM
With
get()
, it will be evaluated every time
empID
is referenced. With
by lazy
it will only be evaluated once at most.
👍 1
If
userModelId
is immutable and
session.getUserModelId()
will always return the same thing, use
by lazy
.
h

hisham bin awiad

10/31/2021, 2:07 PM
Thx bro🌹
r

Robert Williams

11/01/2021, 9:05 AM
Remember
by lazy
also has to synchronise threads on every access to guarantee the single execution
You can remove some of this overhead by using
LazyThreadSafetyMode.NONE
(this will break the single execution guarantee but in this case it probably doesn't matter)
But if the value really is immutable and not particularly expensive to compute but you still only want to do it once you should consider the simple
Copy code
private val empID = (userModelId ?: session.getUserModelId().toSafetyString()).toSafetyString()
1
👍 2
🌹 1
m

Matteo Mirk

11/23/2021, 8:41 AM
minor:
session.getUserModelId()
can be changed to property accessor
session.userModelId
2 Views