https://kotlinlang.org logo
l

LastExceed

05/03/2021, 2:45 PM
is there a way to make a
Map
that's guaranteed to be exhaustive, so the return type of
get()
isn't nullable? (similar to how
when
can skip
else
when it's exhaustive)
r

Rob Elliot

05/03/2021, 2:54 PM
It’s an enum class, isn’t it?
c

christophsturm

05/03/2021, 2:56 PM
or a map with an enum as key
l

LastExceed

05/03/2021, 2:56 PM
the key is an enum. unfortunately i can't just make the associated value a property of that enum
r

Rob Elliot

05/03/2021, 2:57 PM
A when will have the same effect as an exhaustive map. Make it an extension function and it’s almost a property of the enum.
l

LastExceed

05/03/2021, 2:59 PM
the values of the map are computed, using a
when
would mean re-computing the values on every lookup
d

Derek Ellis

05/03/2021, 3:02 PM
l

LastExceed

05/03/2021, 3:04 PM
not really. i guess i have to wrap the map into a container that does a non-null assertion internally
m

mkrussel

05/03/2021, 3:14 PM
Map has a
getValue
method that can be used when you know the key will be in the map.
l

LastExceed

05/03/2021, 3:15 PM
oh thats good to know, ty
e

ephemient

05/03/2021, 4:05 PM
.withDefault()
has the same issue, the typesystem doesn't know that
.get()
can't return null from it
in theory you could define
Copy code
class MyEnumMap(private val delegate: Map<MyEnum, String>) : Map<MyEnum, String> by delegate {
    override fun get(key: MyEnum): String = delegate.getValue(key)
}
but there's some issues with delegation + override in earlier Kotlin versions, so do some investigation to check if it works for you. https://blog.jetbrains.com/kotlin/2020/07/kotlin-1-4-m3-generating-default-methods-in-interfaces/#:~:text=fixing%20an%20issue%20with%20delegates
j

Joost Klitsie

05/04/2021, 9:07 AM
@Derek Ellis that is a great link! I think it would be a great addition to the standard library 🙂
84 Views