LoginSignup
0
0

More than 1 year has passed since last update.

[Tips]Kotlinで使うかもしれない記法

Last updated at Posted at 2021-12-26

備忘録。
今後使うかもしれない記法。
随時更新予定。

コレクションを複数のフィールドを使ってソートする

data class User(
    val id: Long, // ID
    val name: String, // 名前
    val age: Int // 年齢
)

のようなクラスがあったとして、

  • コレクションを「年齢」昇順、「ID」昇順にしたい場合
userList.sortedWith(compareBy({ it.age }, { it.id }))
  • コレクションを「年齢」降順、「ID」降順にしたい場合
userList.sortedWith(compareByDescending<User> { it.age }.thenByDescending { it.id })

空のリストを all() any() などの結果が異なる

  • all() すべての要素がラムダ式で一致するのであればtrue
  • any() いずれかの要素がラムダ式で一致するのであればtrue
  • none() すべての要素がラムダ式で一致しないのであればtrue

リストの中身が空の場合、挙動が異なるので注意。
例えばリストをfilterしたあとに、allなどを実行したい場合、想定と異なる場合があるかもしれない。

    val empty = emptyList<Int>()
    empty.all { it == 1 } // true
    empty.any { it == 1 } // false
    empty.none { it == 1 } // true
0
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
0
0