ru.hnau.jutils.cache.AutoPossibleCache.kt Maven / Gradle / Ivy
package ru.hnau.jutils.cache
import ru.hnau.jutils.possible.Possible
open class AutoPossibleCache(
private val getter: (K) -> Possible,
capacity: Int
) : Cache(
capacity
) {
operator fun get(key: K): Possible = synchronized(this) {
val existenceValue = getValue(key)
if (existenceValue != null) {
return@synchronized Possible.success(existenceValue)
}
val possibleValue = getter.invoke(key)
val possibleData = possibleValue.data
if (possibleData != null) {
putValue(key, possibleData)
}
return@synchronized possibleValue
}
}