Thuta Learning
IntermediateProgrammingbeginner

Functions

Relax. We'll talk through this in plain words — no textbook voice.

A function is a way to name a chunk of code so you can reuse it. Instead of rewriting the same logic in multiple places, you write it once as a function and call it — which keeps your code clean. In Kotlin, you declare a function with the 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.

Summary

Using functions improves code reuse, readability, and testing.

Easy traps

  • If you declare the return type as String but return a number, you'll get a 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

Functions | Thuta Learning