Rob Elliot
08/01/2024, 4:45 PMif (someVar in listOf("value1", "value2", "value3")) {
// do work
}
Like that, I assume the List gets allocated every time the code is run, which seems stupid. But pulling it out into a value somewhere substantially (to my mind) obfuscates the code.
I really want syntax sugar for (someVar == "value1" || someVar == "value2" || someVar == "value3")
, but I don't think that exists?Klitos Kyriacou
08/01/2024, 5:01 PMFrancisco Noriega
08/01/2024, 5:05 PMif(listOf(1,2,3).contains(3)){..}
Klitos Kyriacou
08/01/2024, 5:06 PMin
operator calls contains
.
By the way, I usually write someVar in arrayOf(...)
instead of listOf
- as a naive microoptimization that won't actually make any difference but makes me feel a little bit better because listOf(a, b, c, d)
really compiles to the equivalent of listOf(arrayOf(a, b, c, d))
.Michael Krussel
08/01/2024, 5:15 PMwhen (someVar) {
"value1", "value2", "value3" ->
}
Rob Elliot
08/01/2024, 7:03 PMIdeally the collection of "value1", "value2", and "value3" represents something that you can then use as a named constantAs I said, in my case pulling it out into a value somewhere substantially (to my mind) obfuscates the code
There's also using a when blockThat's really nice - sadly, in my case there's an
&& ...
as well which prevents that.Rob Elliot
08/01/2024, 7:05 PMBy the way, I usually writeI considered that, but sort of vaguely hoped using a read only type would enable some future version of the compiler or runtime to deduce that it could optimise it into a single allocation... allocating an array feels like a more primitive operation that a responsible compiler / runtime will not seek to optimise away.instead ofsomeVar in arrayOf(...)
- as a naive microoptimization that won't actually make any differencelistOf
Rob Elliot
08/01/2024, 7:06 PMPablichjenkov
08/02/2024, 1:53 AMany {}
what you are looking for?
if (list.any {}) {
// Do stuff
}
CLOVIS
08/02/2024, 7:34 AMsome future version of the compiler or runtime to deduce that it could optimise it into a single allocation... allocating an array feels like a more primitive operation that a responsible compiler / runtime will not seek to optimise away.Actually, it's the opposite: arrays are much lower-level and are entirely described by the JVM (you can't make custom subclasses of it) so it's easier for the compiler team to be sure they didn't miss an edge case.
hho
08/02/2024, 7:35 AMCLOVIS
08/02/2024, 7:36 AMsomeVar == "value1" || someVar == "value2" || someVar == "value3"
, it's not hard to read and it's the most efficient ways of doing it 🤷hho
08/02/2024, 7:39 AMin
reads so nice…)CAB
08/02/2024, 7:52 AMwhen
structure.
Finally, in some cases may use the lateinit
value with also meaningful name. In this case it won’t initialized at all unless needed.