Skip to Content
Kotlin📘 Ngôn ngữ Kotlin📍 Local Functions

Local Functions trong Kotlin

🎯 Mục tiêu: Hiểu Local Functions - hàm lồng bên trong hàm khác.


💡 Khái niệm

fun outerFunction() { fun innerFunction() { println("Inner") } innerFunction() // Gọi local function }

📝 Closure - Truy cập biến bên ngoài

fun calculate(numbers: List<Int>): Int { var sum = 0 fun add(n: Int) { sum += n // Truy cập và modify biến bên ngoài } for (n in numbers) { add(n) } return sum }

🎯 Use Case: Validation

fun saveUser(user: User) { fun validate(value: String, fieldName: String) { if (value.isBlank()) { throw IllegalArgumentException("$fieldName cannot be blank") } } validate(user.name, "Name") validate(user.email, "Email") // Save user... }

✅ Checklist

  • Tạo local functions
  • Hiểu closure
  • Sử dụng cho code organization

Last updated on