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