GraphContext.kt
TLDR
The GraphContext.kt
file contains a class GraphContext
which is an in-memory store that can be used to store objects in a HeapGraph
instance. It is implemented as a simple MutableMap
of String
keys to Any
values.
Methods
get
The get
method allows retrieving a value from the store by providing a key. It returns the value cast to the requested type T
, or null
if the key does not exist in the store.
getOrPut
The getOrPut
method is similar to MutableMap.getOrPut
. It retrieves the value associated with the given key if it exists, otherwise it sets a default value in the store by invoking defaultValue
and returns that value. It is useful for lazy initialization of values in the store.
set
The set
method allows adding or updating a key-value pair in the store. The value must be of type T
.
contains
The contains
method checks if a key exists in the store. It returns true
if the key is present, false
otherwise.
minusAssign
The minusAssign
method allows removing a key-value pair from the store by providing the key. It performs the same function as the MutableMap.remove
method.
END
package shark
/**
* In memory store that can be used to store objects in a given [HeapGraph] instance.
* This is a simple [MutableMap] of [String] to [Any], but with unsafe generics access.
*/
class GraphContext {
private val store = mutableMapOf<String, Any?>()
operator fun <T> get(key: String): T? {
@Suppress("UNCHECKED_CAST")
return store[key] as T?
}
/**
* @see MutableMap.getOrPut
*/
fun <T> getOrPut(
key: String,
defaultValue: () -> T
): T {
@Suppress("UNCHECKED_CAST")
return store.getOrPut(key) {
defaultValue()
} as T
}
/**
* @see MutableMap.set
*/
operator fun <T> set(
key: String,
value: T
) {
store[key] = (value as Any?)
}
/**
* @see MutableMap.containsKey
*/
operator fun contains(key: String): Boolean {
return key in store
}
/**
* @see MutableMap.remove
*/
operator fun minusAssign(key: String) {
@Suppress("UNCHECKED_CAST")
store -= key
}
}