https://kotlinlang.org logo
Title
v

vmichalak

06/09/2017, 6:02 AM
Hi all, do you know if message: String = "Hello $name" is lazy evaluated by default or not ? It's for optimisation purpose :)
o

orangy

06/09/2017, 6:04 AM
@vmichalak what do you mean by lazy here?
v

vmichalak

06/09/2017, 6:07 AM
The string concatenation between "Hello " and $name is made at the last moment or not ? (Sorry for my english 😣)
n

noctarius

06/09/2017, 6:15 AM
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

orangy

06/09/2017, 6:16 AM
Type of
message
is
String
, so it has to do a full build to assign it.
n

noctarius

06/09/2017, 6:18 AM
@orangy but I guess for a constant it’ll do compile time resolution? 🙂
o

orangy

06/09/2017, 6:19 AM
No, it would be complicated and unpredictable, because it might need to call
toString
on
name
n

noctarius

06/09/2017, 6:20 AM
right, fair point 🙂
o

orangy

06/09/2017, 6:24 AM
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

noctarius

06/09/2017, 6:25 AM
I thought more about the “make a constant really constant”, not ending up in the same situation as Java with final 😉
k

kirillrakhman

06/09/2017, 6:54 AM
@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

vmichalak

06/09/2017, 7:02 AM
Thanks a lot Kirill ! It's exactly what i search