LoginSignup
47
38

More than 5 years have passed since last update.

Kotlinのif let

Last updated at Posted at 2015-09-17

swiftだとおなじみの1文

let name: String? = "John Doe"

if let it = name {
  print("Name: \(it)")
}

kotlinだと次のように書ける

val name: String? = "John Doe"

name?.let {
   print("Name: ${it}")
}

これは引数を安全にunwrapしたいときにべんり。
またletは返り値がきちんととれるので、optionalな値をoptionalでない値に操作する時にも便利.

たとえば、3項演算が必要な場合

val number: Int? = null
val twoTimesNumber = if (number != null) number * 2 else 0

nil coalescing operatorと組み合わせると、if-else をかくよりもすっきりする.

val twoTimesNumber = number?.let { it * 2 } ?: 0 
47
38
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
47
38