Let's say I have a
enum class ConceptualPosition{
A1,A2,A3,A4,A5,A6,A7,A8,
B1,B2,B3,B4,B5,B6,B7,B8,
C1,C2,C3,C4,C5,C6,C7,C8
}
And I now want to construct a Graph where every position has a Node.
import [...].domain.model.base.ConceptualPosition
import [...].domain.model.base.ConceptualPosition.*
import [...].domain.model.base.Node
import [...].domain.model.base.Node.MovableDirection.*
class MyGraph:Graph{
private val internalPositions = mutableMapOf<ConceptualPosition, Node>()
override val position by lazy {internalPositions.toMap().withDefault {
throw IllegalArgumentException("position '$it' does not exist")
}}
init{
//create nodes for all positions
ConceptualPosition.values().forEach { internalPositions[it] = Node(it) }
//now build graph
position[A1]!!.connectBothWaysWith(position[A2]!!,RIGHT)
position[A2]!!.connectBothWaysWith(position[A3]!!,RIGHT)
[...]
}
}
since I have a withDefault
that immediately throws an exception and since Kotlin correctly infers the type of position
to be Map<ConceptualPosition,Node>
, I think I can be fairly sure that if a lookup does not fail, I get a non-null value out of it.
Kotlin apparently cannot safely infer that.
Can I refactor this (in a reasonable way) to get rid of the !!
?
Use Map.getValue
instead of get
:
position.getValue(A1).connectBothWaysWith(position.getValue(A2),RIGHT)
Alternately, you could define your own version of withDefault
with a more precise return type (the Kotlin standard library makes the equivalent private):
class MapWithDefault<K, V>(val map: Map<K, V>, val default: (K) -> V) : Map<K, V> by map {
override fun get(key: K): V = map[key] ?: default(key)
}
fun <K, V> Map<K, V>.withDefault(default: (K) -> V) = MapWithDefault(this, default)