1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

kotlinでリストのアップデートを共通化

Posted at

初めに

今回はKotlinでリストのアップデート処理を紹介してきます

本文

さっそくですが、下記がコードになります
リストの中身はジェネリックにしてどんな型でも受け取れるようにします。
判定基準とアップデート内容を引数にとることで共通化することができます

fun <T> MutableList<T>.updateIf(predicate: (T) -> Boolean, transform: (T) -> T) {
    for (i in indices) {
        if (predicate(this[i])) {
            this[i] = transform(this[i])
        }
    }
}

さいごに

いろいろなところで書くのが煩わしいので共通化してみました
どなたかのお役に立てれば幸いです

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?