is there a `SortedMap` equivalent that is a pure K...
# getting-started
y
is there a
SortedMap
equivalent that is a pure Kotlin type (and so doesn’t use platform types)?
s
y
thanks. what is the attitude about passing around Java containers (which are by definition not type safe)? is it discouraged in production code?
r
Most containers are Java containers -
listOf
and
mapOf
both return Java lists and maps
s
Mostly it’s okay, because Kotlin knows about the different map and collection types from Java. In the case of
SortedMap
, all of the methods it inherits from the
Map
and
MutableMap
interfaces will have proper Kotlin nullability information.
y
I’m asking because I noticed a bug in code I’ve just written, where I try to do
someMap[idx] = foo
where
someMap
is
SortedMap<K,V>
and
foo
is
V?
, but was not warned
s
Interesting, I wouldn’t have expected that. I can reproduce the same problem, though. Looks like if I declare the type as
SortedMap<K, V>
it lets me try to add null values, but if I declare it as
MutableMap<K, V>
(the Kotlin type) it doesn’t.
😞
y
indeed
was rather surprising (but understandable)
r
Odd: Compile error:
Copy code
val map: TreeMap<String, String> = TreeMap()
val x: String? = "s"
map[x] = "s"
Compiles:
Copy code
val map: SortedMap<String, String> = TreeMap()
val x: String? = "s"
map[x] = "s"
If
TreeMap
can inherit Kotlin's nullability semantics from
Map
I'd have thought
SortedMap
could, but evidently not.
y
interesting. so, disregarding this strange behavior for a second, can I have equivalent code, but with compiler-enforced null checks, by using
TreeMap
instead of
SortedMap
?
r
I mean, my 2 minutes of testing in a scratch.kts in IntelliJ suggests you can, but other than that I haven't a clue 🙂
y
very helpful, thanks everyone.
d
If
TreeMap
can inherit Kotlin's nullability semantics from Map I'd have thought
SortedMap
could, but evidently not.
TreeMap
is a specific implementation, and Kotlin knows that it treats nullability carefully. But
SortedMap
is a generic interface, and there are no guarantees, that someone would provide incorrect implementation of it. So that's why
TreeMap
works well and
SortedMap
doesn't
👍 4
e
aside, I find it somewhat disappointing that Java has a built-in rbtree instead of a b-tree since the latter can support all the same operations with a (generally) lower overhead
s
TreeMap
is a specific implementation, and Kotlin knows that it treats nullability carefully. But
SortedMap
is a generic interface, and there are no guarantees, that someone would provide incorrect implementation of it.
This explanation does make sense, except that
TreeMap
isn’t a final class. In the same way that someone could provide an “incorrect” implementation of
SortedMap
, couldn’t they do the same thing by extending
TreeMap
?
d
Yes, it is true. But it is just a pragmatic assumption, that there is a quite low probability that someone will extend
java.util.TreeMap
and change its behavior on null keys and values
👍 1