IntermediateProgrammingbeginner
Functions
စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။
Function ဆိုတာ code အပိုင်းတစ်ခုကို နာမည်ပေးပြီး ပြန်သုံးနိုင်အောင်လုပ်တဲ့နည်းပါ။ တူညီတဲ့ logic ကိုနေရာအများကြီးမှာ ထပ်ရေးမည့်အစား function တစ်ခုတည်းရေးပြီး ခေါ်သုံးတာက code ကိုသန့်စင်စေပါတယ်။ Kotlin မှာ function ကို fun keyword နဲ့ကြေညာပါတယ်။
kotlin
fun greet(name: String, day: String = "Sunday"): String {
return "Hello $name, today is $day."
}
fun main() {
println(greet("Aung"))
println(greet("Hla", "Monday"))
}
You should see
Hello Aung, today is Sunday. Hello Hla, today is Monday.
အနှစ်ချုပ်
Function သုံးခြင်းက code reuse, readability, testing ကိုပိုကောင်းစေပါတယ်။
ဒီနေရာမှာ လူအများမှားတတ်တယ်
- Return type ကို String လို့ရေးထားပြီး number return ပြန်ရင် type mismatch error ဖြစ်ပါမယ်။
Practical example — discount calculator
Practical example — discount calculator
kotlin
fun calculateFinalPrice(price: Double, discountPercent: Double): Double {
val discountAmount = price * discountPercent / 100
return price - discountAmount
}
fun main() {
val finalPrice = calculateFinalPrice(50000.0, 10.0)
println("Final price: $finalPrice MMK")
}
You'll know it worked when: Final price: 45000.0 MMK