Mark Fisher
12/29/2020, 10:21 AMinterface HexData
object EmptyHexData : HexData
data class Hex(val q: Int, val r: Int, val s: Int)
interface HexDataStorage<T: HexData> {
fun addHex(hex: Hex)
fun addHex(hex: Hex, data: T): Boolean
}
class DefaultHexDataStorage<T: HexData> : HexDataStorage<T> {
private val storage = LinkedHashMap<Hex, T>()
override fun addHex(hex: Hex) {
storage[hex] = EmptyHexData // <-- ERROR
}
override fun addHex(hex: Hex, data: T): Boolean {
val previous = storage.put(hex, data)
return previous != null
}
}
In the function addHex(hex: Hex), I cannot use "EmptyHexData", and I don't understand why. AFAIU It's a sub-type of HexData, so I thought it would comply with the requirement of being a T
in this case. What's wrong, and how do I fix it?
I tried using a class too, e.g. class EmptyHexDataClass: HexData
but that didn't work either.Giorgos Neokleous
12/29/2020, 10:32 AMinterface HexDataStorage {
fun addHex(hex: Hex)
fun addHex(hex: Hex, data: HexData): Boolean
}
class DefaultHexDataStorage : HexDataStorage {
private val storage = LinkedHashMap<Hex, HexData>()
override fun addHex(hex: Hex) {
storage[hex] = EmptyHexData
}
override fun addHex(hex: Hex, data: HexData): Boolean {
val previous = storage.put(hex, data)
return previous != null
}
}
Yev Kanivets
12/29/2020, 10:33 AMaddHex(hex: Hex)
takes Hex
, not T
, and EmptyHexData
doesn’t inherit from Hex
, but from HexData
.Vampire
12/29/2020, 10:34 AMMark Fisher
12/29/2020, 10:34 AMVampire
12/29/2020, 10:35 AMT
is HexData
or a subtype of itinterface MyHexData : HexData
and then have a DefaultHexDataStorage<MyHexData>
that would be legalEmptyHexData
as it is a HexData
, but not a MyHexData
EmptyHexData
but T
was expected"Mark Fisher
12/29/2020, 10:37 AMVampire
12/29/2020, 10:37 AMMyHexData
as I just explainedDefaultHexDataStorage<MyHexData>
your map will have runtime type LinkedHashMap<Hex, MyHexData>
and EmptyHexData
is not a MyHexData
but a siblingMark Fisher
12/29/2020, 10:39 AMVampire
12/29/2020, 10:40 AMMaybe
whatever that should be.Mark Fisher
12/29/2020, 10:41 AMRob Elliot
12/29/2020, 11:11 AMnull
to represent `EmptyHexData`:
private val storage = LinkedHashMap<Hex, T?>()
override fun addHex(hex: Hex) {
storage[hex] = null
}
Mark Fisher
12/29/2020, 2:52 PMprivate val storage = LinkedHashMap<Hex, Maybe<T>>()
override fun addHex(hex: Hex) {
storage[hex] = Maybe.empty()
}
override fun addHex(hex: Hex, data: T): Boolean {
val previous = storage.put(hex, Maybe.of(data))
return previous != null
}
Although my current implementation doesn't need generics, so I've stripped it back to simple HexData types directly.Vampire
12/29/2020, 2:56 PMMark Fisher
12/29/2020, 2:58 PMYoussef Shoaib [MOD]
12/29/2020, 3:37 PMIO
wrapper since the compiler automatically tracks effects with suspend)Nir
12/29/2020, 3:40 PM