Skip to content

Commit

Permalink
Renamed to getOrNull
Browse files Browse the repository at this point in the history
  • Loading branch information
sksamuel committed Dec 28, 2023
1 parent b61049f commit 0dce3ff
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ class Cache<K, V>(
* @param compute the suspendable function to generate a value for the given key.
* @return the present value, the computed value, or throws.
*/
suspend fun computeIfAbsent(key: K, compute: suspend (K) -> V?): V? {
suspend fun getOrNull(key: K, compute: suspend (K) -> V?): V? {
val scope = scope()
return cache.get(key) { k, _ -> scope.async { compute(k) }.asCompletableFuture() }.await()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,17 +50,17 @@ class CacheTest : FunSpec() {

test("Cache should support computeIfAbsent") {
val cache = caffeineBuilder<String, String>().build()
cache.computeIfAbsent("foo") {
cache.getOrNull("foo") {
yield()
"bar"
} shouldBe "bar"
val key = "baz"
cache.computeIfAbsent(key) { null }.shouldBeNull()
cache.computeIfAbsent(key) { "new value" }.shouldBe("new value")
cache.computeIfAbsent(key) { "new value 2" }.shouldBe("new value")
cache.computeIfAbsent(key) { null }.shouldBe("new value")
shouldNotThrowAny { cache.computeIfAbsent(key) { error("kapow") } }
shouldThrow<IllegalStateException> { cache.computeIfAbsent("not present") { error("kapow") } }
cache.getOrNull(key) { null }.shouldBeNull()
cache.getOrNull(key) { "new value" }.shouldBe("new value")
cache.getOrNull(key) { "new value 2" }.shouldBe("new value")
cache.getOrNull(key) { null }.shouldBe("new value")
shouldNotThrowAny { cache.getOrNull(key) { error("kapow") } }
shouldThrow<IllegalStateException> { cache.getOrNull("not present") { error("kapow") } }
}

test("cache should propagate exceptions in the getAll compute function override") {
Expand Down

0 comments on commit 0dce3ff

Please sign in to comment.