Robert
10/08/2019, 4:27 PMMap
? I tried extending HashMap
but it is final. When I extend Map
I have to implement all types of body functions like containsKey
, containsValue
, get
, isEmpty
and properties entries
, keys
, size
and values
Alowaniak
10/08/2019, 4:42 PMdelegate
by?ilya.gorbunov
10/08/2019, 4:48 PMRobert
10/08/2019, 4:49 PMShawn
10/08/2019, 5:09 PMRobert
10/08/2019, 5:24 PMAbstractMap
, how do I set the initial values? As I can't use mapOf
to bootstrap it..Ruckus
10/08/2019, 5:33 PMrobertMapOf(vararg Pair<K, V>)
or Map<K, V>.toRobertMap()
Matteo Mirk
10/09/2019, 7:44 AMStephan Schroeder
10/09/2019, 12:21 PMRobert
10/09/2019, 6:57 PMcontains
etc. Instead I just extend the existing class with methods and add some new ones. I don't see how that is "wrong".apply
. I don't have and putAll
method or something, as it's a normal map
class RobertMap: AbstractMap<Int, String>() {
override val entries: Set<Map.Entry<Int, String>>
get() = throw UnsupportedOperationException()
}
public fun <Int, String> robertMapOf(vararg pairs: Pair<Int, String>): RobertMap = RobertMap(pairs.size).apply {}
mapOf
does this, which seems to create a LinkedHashMap by default? if (pairs.size > 0) pairs.toMap(LinkedHashMap(mapCapacity(pairs.size))) else emptyMap()
Ruckus
10/09/2019, 7:14 PMclass RobertMap(vararg entries: Pair<Int, String>) : AbstractMap<Int, String>() {
override val entries: Set<Map.Entry<Int, String>> =
Collections.unmodifiableSet(entries.mapTo(mutableSetOf()) { Entry(it.first, it.second) })
private class Entry(override val key: Int, override val value: String) : Map.Entry<Int, String>
}
which would let you use
val map = RobertMap(1 to "one", 2 to "two", ...)
Robert
10/09/2019, 7:18 PMColletions
but maybe that's because I'm in a MP project.
So I thought an unmodifiable Map would be cheaper than a mutable one. But from the code I guess this is not true; as it is change to mutableSet before it becomes the unmodifiable set?Ruckus
10/09/2019, 8:03 PMCollections.unmodifiableSet
is a Java stdlib function. I was optimizing for readability / LOC. You could save it more efficiently and use your own implementation of an abstract set to access it.Matteo Mirk
10/10/2019, 2:57 PMAbstractMap
, but it’s seldom the case. If instead you need a domain object that can be backed by a map, then I strongly advise to use composition and create your domain-specific interface, which of course won’t replicate any of the Map’s interface. If you need more explanation I can provide some code example, just ask.