LoginSignup
11
9

More than 5 years have passed since last update.

KotlinでHashMapをキャッシュとして使うときに便利なやつ

Posted at

HashMap#getOrPutという素晴らしいメソッドが生えていたことに最近気づいた。

val cache = hashMapOf<Int, Hoge>()

fun getHoge(key: Int): Hoge {
    return this.cache.getOrPut(key) {
        // なにやらこねくり回したりしてデータを作る
        Hoge(key)
    }
}

Kotlinだと最後の引数のlambdaは()の外に書けて可読性が良い感じ。

11
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
9