Skip to content

A withDefault extension function #54

@andrew-at-rm

Description

@andrew-at-rm

Basically something the same as https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.collections/with-default.html

Not sure if it would be as simple as below

class CacheWithDefault<K : Any, V : Any>(
    val cache: Cache<K, V>,
    private val default: (K) -> V?
) : Cache<K, V> by cache {
    override fun get(key: K): V? = cache.get(key) ?: default(key)?.also { cache.put(key, it) }
}

fun <K : Any, V : Any> Cache<K, V>.withDefault(defaultValue: (K) -> V?): Cache<K, V> = when (this) {
    is CacheWithDefault -> this.cache.withDefault(defaultValue)
    is Cache -> CacheWithDefault(this, defaultValue)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions