28 Temmuz 2021 Çarşamba

Kotlin let Anahtar Kelimesi

Açıklaması şöyle
let is treated as a native way to do null checks on the variables.

Please don’t do that even if using `let` feels functionally beautiful but

- You will end up creating another reference called it in the same scope which is less descriptive
- To fix that you will definitely try to provide an explicit parameter for lambda example imageFile?.let{ image →,
- but it creates a load of finding another name for the same variable (naming things are hard)
- Now other devs can refer to image files in the scope with two names imageFile and image, with time you need to maintain that the right variable is being used inside the scope of lambda when there is iteration over the code for bugs and changes.
Örnek - null check
Birinci maddeyi gösteren bir kod şöyle
fun deleteImage(){
   var imageFile : File ? = ...
   imageFile?.let { // ❌ don't write code like this
      if(it.exists()) it.delete()
   }
}
Bu yöntem illaki kullanılacaksa "it" yerine düzgün bir isim verilebilir. Şöyle yaparız
class Foo {
  var imageFile : File ? = ...
  fun deleteImage(){
      // 🧐 you can get away for now
      imageFile?.let { image ->
        if(image.exists()) image.delete()
      }
  }
}

Hiç yorum yok:

Yorum Gönder