Hi all, do you know if message: String = "Hello $n...
# getting-started
v
Hi all, do you know if message: String = "Hello $name" is lazy evaluated by default or not ? It's for optimisation purpose :)
o
@vmichalak what do you mean by lazy here?
v
The string concatenation between "Hello " and $name is made at the last moment or not ? (Sorry for my english 😣)
n
It is done the second you do the assignment
the string
name
might change afterwards, so it cannot be lazy and it cannot be done ahead of time, except
name
would be a constant
o
Type of
message
is
String
, so it has to do a full build to assign it.
n
@orangy but I guess for a constant it’ll do compile time resolution? šŸ™‚
o
No, it would be complicated and unpredictable, because it might need to call
toString
on
name
n
right, fair point šŸ™‚
o
well, thinking about it a bit more (early morning, not yet even coffee), const types can only be primitives, String and may be classes, so may be it’s possible. But not sure it’s really needed. If performance is critical, you can always cache it yourself.
šŸ‘ 2
n
I thought more about the ā€œmake a constant really constantā€, not ending up in the same situation as Java with final šŸ˜‰
k
@vmichalak if your usecase is logging or preconditions, you can use an inline lambda, like in
require(person.age >= 18) { "$person must be over 18 years old." }
in this example, the string is only constructed, when the condition is false and an exception is thrown. otherwise the code is never executed.
v
Thanks a lot Kirill ! It's exactly what i search