Can I assume a `mutableMapOf()` to preserve iterat...
# announcements
m
Can I assume a
mutableMapOf()
to preserve iteration order on key re-insertion like a LinkedHashMap ?
r
no you can’t
👍 1
s
Would be nice of them to provide that guarantee though
m
That answers it, thanks
It's very tempting to assume it
r
linkedMapOf()
3
boom
m
On the JVM it's all the same
mutableMapOf()
calls
LinkedHashMap()
which is why it's very tempting to assume the same API as
LinkedHashMap
But maybe on other platforms it's different?
s
LinkedHashMap
is a kotlin type
m
Doesn't it alias on the JVM?
mmm, right no it doesn't
s
Pretty sure it does
m
ok yes, it makes sense then 👍
s
There are no docs though so its hard to say but seems pretty safe assumption that it will be identical to javas on all platforms
Maybe a question for #stdlib
👍 1
n
I feel like, even if the assumption is "safe" it's still better to use the more specific function, and even type
it documents intent, and also, it may end up protecting your code (depending on how things are written, or modified in the future)
☝️ 2
m
The question whether
LinkedHashMap
keeps order on re-insertion remains
r
Why does the order matter for a map?
s
A workaround could be to assume so and make a test that verifies in order to guard against it giving you a heads up
n
Sorry can you clarify "re-insertion"
are you saying, if you do
x["foo"] = 5
if "foo" is already present in the hash table, then you want the value to be changed, but not the order?
m
@Nir yes, exactly
The JVM LinkedHashMap has a specific note about it but it's not mentioned in the Kotlin doc
n
yeah, guess you'd need to ask the stdlib maintainers to clarify that point
you're interested in all 3 targets?
m
TBH, the code only runs on the JVM at the moment but I like to write something that's as platform agnostic as possible as it might be compiled to native at some point
s
2
m
Thanks !
n
A good workaround for now might be to create an alias, and use that. If it turns out that the native type does not give the guarantees you need, you should be able to change the alias (hopefully conditionally if necessary)
I'd probably also clarify what's meant by "assume order of re-inserted keys", because allowing users to assume that the order is that re-inserted keys get moved to the front is also a valid choice
g
no you can't
This is incorrect! Please check documentation of this function: The returned map preserves the entry iteration order.
m
The "key" (pun intended 🙃) word up there is "re-insertion"
For now I'll keep iterate
Lists
I think, it's a bit more verbose/less optimal I think but at least it'll make it explicit that the order is kept
n
@mbonnin that's a bit tricky to get right
in the face of deletions