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

Constructors

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

Constructor ဆိုတာ object ဖန်တီးတဲ့အချိန်မှာ initial data ထည့်ပေးနိုင်တဲ့ class setup ပုံစံပါ။ Kotlin မှာ primary constructor ကို class name နောက်မှာတိုက်ရိုက်ရေးနိုင်တာကြောင့် code တိုပြီးရှင်းပါတယ်။

kotlin
class Person(val firstName: String, var age: Int)

fun main() {
    val person = Person("John", 35)
    println("${person.firstName} is ${person.age} years old.")
}
You should see
John is 35 years old.

အနှစ်ချုပ်

Constructor က object တစ်ခုကို စတင်ဖန်တီးတဲ့အချိန် data မှန်မှန်ထည့်ပေးဖို့ အရေးကြီးပါတယ်။

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

  • Constructor parameter order မှားထည့်ရင် data meaning မှားနိုင်ပါတယ်။ Named argument သုံးရင်ပိုရှင်းပါတယ်။

Practical example — named arguments

Practical example — named arguments

kotlin
class Course(val title: String, val durationHours: Int)

fun main() {
    val course = Course(
        title = "Kotlin Foundation",
        durationHours = 12
    )

    println("${course.title}: ${course.durationHours} hours")
}

You'll know it worked when: Kotlin Foundation: 12 hours

Constructors | Thuta Learning