Thuta Learning
ရှာဖွေရန်
BasicProgrammingbeginner

Safe Calls & Elvis Operator

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

Nullable value ကိုအသုံးပြုတဲ့အခါ crash မဖြစ်အောင် safe call operator ?. နဲ့ Elvis operator ?: ကိုသုံးပါတယ်။ ဒီနှစ်ခုကိုနားလည်ထားရင် API response, optional user profile data, database field တွေကိုပိုလုံခြုံစွာကိုင်တွယ်နိုင်ပါတယ်။

kotlin
fun main() {
    val name: String? = null

    val length = name?.length
    println("Length: $length")

    val displayName = name ?: "Guest User"
    println("Welcome, $displayName")
}
You should see
Length: null Welcome, Guest User

အနှစ်ချုပ်

Nullable value ကိုတိုက်ရိုက်မကိုင်ပါနဲ့။ ?. နဲ့ ?: ကိုသုံးပြီး safe path ပြုလုပ်ပါ။

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • name!!.length ကိုမလိုအပ်ဘဲသုံးရင် name null ဖြစ်တဲ့အခါ crash ဖြစ်နိုင်ပါတယ်။

Practical example — profile bio

Practical example — profile bio

kotlin
fun main() {
    val bio: String? = null
    val shortBio = bio?.take(20) ?: "No bio added yet"

    println(shortBio)
}

You'll know it worked when: No bio added yet

Safe Calls & Elvis Operator | Thuta Learning