1

I want to write a null check code in a fancy way . Is there a better way to write? Some sample or tips will be great! I would love to hear from you!

if (list != null) {
    myData = list[0]
}
Nancy
  • 129
  • 2
  • 13

1 Answers1

2

A more functional style of writing this is using let together with the ? operator:

list?.let { myData = it[0] }

Using ?, let is only called if 'list' is not null and list is passed as the only parameter to the lambda.

Alexander Egger
  • 5,132
  • 1
  • 28
  • 42
  • 1
    Additionally, when you need else branch, you can simply put `?: "some else value"` after brace end: `list?.let { myData = it[0] } ?: myData = "some else value"` and having this, you can even make it better by moving `myData` to the beginning: `myData = list?.let { it[0] } ?: "some else value"` – dey Apr 04 '19 at 05:52