y
11/14/2022, 9:20 AMList<String>
, can I expect Kotlin to reuse this list, or will it allocate on every call to the function?Jakub Syty
11/14/2022, 9:21 AMy
11/14/2022, 9:22 AMlistOf("literal1", "literal2", …)
y
11/14/2022, 9:22 AMLoney Chou
11/14/2022, 9:45 AMMichael de Kaste
11/14/2022, 9:46 AMfun getList() = listOf("literal1", "literal2")
then it will create one every time.
It might be better to save the list in the class itself in the companion object.y
11/14/2022, 9:56 AMIlya K
11/14/2022, 10:59 AMval list = listOf("literal1", "literal2")
y
11/14/2022, 11:09 AMMichael de Kaste
11/14/2022, 11:10 AMMichael de Kaste
11/14/2022, 11:10 AMStephan Schroeder
11/14/2022, 11:26 AMprivate val list = listOf("literal1", "literal2")
fun getList(): List<String> = list
And since List
is an immutable interface, you're pretty safe that you won't run into multiple parts of the programm modifying their list and screwing up everybody else (they could technically do that by first casting their instance to MutableList
).
Normally this level of contract ("don't cast") is good enough, if it's not, you can use immutable collections from https://github.com/Kotlin/kotlinx.collections.immutabley
11/14/2022, 12:07 PMstatic
variables.gildor
11/14/2022, 2:54 PMy
11/14/2022, 2:54 PMprivate val someList = listOf(…)
as a class property. no intermediate function. just like I do for Regex
objects to avoid recreating them. only issue is that it pollutes the class-level namespace, but eh.y
11/14/2022, 2:57 PMgildor
11/14/2022, 3:15 PMStephan Schroeder
11/15/2022, 9:00 AMList
to MutableList
as another optimization thereby opening a can of worms. Simply creating a new list each time protects you of such future optimization interactions.y
11/15/2022, 9:03 AMRegex
objects? creating these tends to be expensive in other languages.gildor
11/15/2022, 9:10 AMStephan Schroeder
11/15/2022, 10:09 AM