Belajar Nullable Receiver di Kotlin

Dhe997

Menariknya, kita bisa juga mendeklarasikan sebuah extension dengan nullable receiver type. Alhasil, extension tersebut bisa dipanggil pada objek yang bahkan nilainya null.


  1. val Int?.slice: Int

  2.     get() = if (this == null) 0 else this.div(2)


If expression pada contoh di atas adalah untuk memeriksa apakah receiver object-nya bernilai null. Jika tidak bernilai null, maka receiver object tersebut akan secara otomatis di-casting menjadi tipe non-null, sehingga kita bisa menggunakan nilainya.
Selain menggunakan if expression, kita juga bisa menggunakan elvis operator. Misalnya seperti berikut:

  1. val Int?.slice: Int

  2.     get() = this?.div(2) ?: 0


Untuk memanggilnya pun sama seperti extension properties sebelumnya.

  1. fun main() {

  2.     val value: Int? = null

  3.  

  4.     println(value.slice)

  5. }

  6.  

  7. val Int?.slice: Int

  8.     get() = this?.div(2) ?: 0

  9.  

  10. /*

  11.    output : 0

  12. */


Lalu kapan kita membutuhkannya? Tentunya jika kita mempunyai sebuah objek yang bernilai null. Saat kita tidak menetapkannya dengan nullable receiver type, maka kita perlu memeriksa apakah objek tersebut bernilai null atau tidak? Bisa juga dengan menggunakan operator safe call setiap kali extension tersebut dipanggil. Contohnya seperti berikut:

  1. fun main() {

  2.     val value: Int? = null

  3.     val value1: Int? = null

  4.  

  5.     println(value?.slice)

  6.     println(value1?.slice)

  7. }

  8.  

  9. val Int.slice: Int

  10.     get() = this.div(2)

  11.  

  12. /*

  13.    output : null

  14.             null

  15.  

  16. */


Kita juga bisa menentukan nilai dari receiver object jika bernilai null. Sehingga kita tidak perlu lagi menggunakan operator safe call ketika ingin memanggil extension tersebut.

  1. fun main() {

  2.     val value: Int? = null

  3.     val value1: Int? = null

  4.  

  5.     println(value.slice)

  6.     println(value1.slice)

  7. }

  8.  

  9. val Int?.slice: Int

  10.     get() = this?.div(2) ?: 0

  11.  

  12. /*

  13.    output : 0

  14.             0

  15.  

  16. */


Posting Komentar

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.