LoginSignup
0
0

More than 1 year has passed since last update.

Kotlin firstOrNullの使い方について

Posted at

実務でfirstOrNullのメソッド使う時があったため備忘録としてここにメモしておきます

//以下のようなlistがあった場合に頭の1を取得したい場合に`firstOrNull`や`first`を使います

val list = listOf("1", "2", "3","1")
list.firstOrNull { 1 == it.1}

fist,firstOrNullの違いについて

val list = listOf("1", "2", "3","1")
list.first {2 == it.4}
//listの中に4がないのでnullになりおちます

list.firstOrNull {2 == it.4}
//listのなかに4はありませんが、該当する値がない場合はnullをあつかってくれるので、あらかじめnull許容にしておけば問題ありません

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