is there a kotlin native way to have a `SortedMap`...
# kotlin-native
r
is there a kotlin native way to have a
SortedMap
? E.g., when I'm deserializing a
json
map where the order is important 🙂 It seems that
Map
happens to be sorted, but I assume it's the same as for Java - there is no guarantee it will stay that way, am I correct in that assumption? If so what can/should I do?
e
I am not sure which behavior you are talking about
Kotlin/JVM has a
.toSortedMap()
extension function, which returns a
java.util.SortedMap
. this is a map whose keys are always iterated in comparator order. this is not available on Kotlin/Native
most of the
Map
-returning functions in Kotlin stdlib return an order-preserving map: entries are iterated in insertion order (
kotlin.collections.HashMap
being an exception and explicitly guaranteeing no particular order)
do you actually want a
SortedMap
, e.g.
Copy code
mapOf("b" to 1, "a" to 2).toSortedMap().entries.toList() // [a=2, b=1]
or do you want an order-preserving map, e.g.
Copy code
mapOf("b" to 1, "a" to 2).entries.toList() // [b=1, a=2]
if you are using kotlinx.serialization, the default
Map
deserialization uses
LinkedHashMap
, which preserves order
r
good point, I see the difference. What I want is an order preserving map indeed 🙂 and I am using kotlinx.serialization, so sounds like I'm well off already 🙂 can I trust that it will stay an order preserving map (would make sense to me, but some times there are reasons 😉 )?
e
I would expect so - that is the behavior of all standard maps across all of Kotlin, and I would consider a change to that to be breaking - but it doesn't appear to be documented in kotlinx.serialization
m
It is documented here for example: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/mutable-map-of.html
Copy code
The returned map preserves the entry iteration order.
r
nice, thanks 🙂
e
right, it's documented on the Kotlin stdlib side, but there's nothing in the kotlinx.serialization documentation (as far as I can see) that states that it's using that when decoding JSON
m
But it would be strange if not, wouldn’t it?
r
@Michael Paus it would, but it's programming, I mean I've seen people do some weird things
668 Views