Skip to Content

Hàm (Function) trong Kotlin

1. Định nghĩa hàm cơ bản

fun sayHello() { println("Hello, Kotlin!") } fun main() { sayHello() // Gọi hàm }

2. Hàm với tham số

fun greet(name: String) { println("Hello, $name!") } fun main() { greet("Alice") greet("Bob") }

2.1. Nhiều tham số

fun sum(a: Int, b: Int) { println("$a + $b = ${a + b}") } fun main() { sum(5, 3) // 5 + 3 = 8 }

3. Hàm có giá trị trả về

fun sum(a: Int, b: Int): Int { return a + b } fun main() { val result = sum(10, 20) println(result) // 30 }

3.1. Single-expression function

fun sum(a: Int, b: Int): Int = a + b // Có thể bỏ kiểu trả về (type inference) fun sum(a: Int, b: Int) = a + b

4. Tham số mặc định

fun greet(name: String = "Guest", greeting: String = "Hello") { println("$greeting, $name!") } fun main() { greet() // Hello, Guest! greet("Alice") // Hello, Alice! greet("Bob", "Hi") // Hi, Bob! greet(greeting = "Hey") // Hey, Guest! (named argument) }

5. Named arguments

fun createUser(name: String, age: Int, city: String) { println("Name: $name, Age: $age, City: $city") } fun main() { // Gọi theo thứ tự createUser("Alice", 25, "Hanoi") // Named arguments - rõ ràng hơn createUser( name = "Bob", age = 30, city = "HCMC" ) // Có thể đổi thứ tự createUser( age = 22, city = "Danang", name = "Charlie" ) }

6. Vararg - Số lượng tham số không xác định

fun sum(vararg numbers: Int): Int { var total = 0 for (num in numbers) { total += num } return total } fun main() { println(sum(1, 2, 3)) // 6 println(sum(1, 2, 3, 4, 5)) // 15 println(sum(10)) // 10 }

7. Unit - Hàm không trả về giá trị

// Cách 1: Khai báo Unit fun printMessage(): Unit { println("Message") } // Cách 2: Bỏ qua Unit (khuyến nghị) fun printMessage() { println("Message") }

8. Hàm Nothing - Không bao giờ return

fun fail(message: String): Nothing { throw IllegalStateException(message) } fun validateAge(age: Int) { if (age < 0) { fail("Age cannot be negative") } }

9. Local functions (Hàm nội)

fun outerFunction(x: Int) { fun innerFunction(y: Int): Int { return x + y } println(innerFunction(5)) }

10. Infix functions

infix fun Int.times(str: String) = str.repeat(this) fun main() { println(3 times "Hello ") // Hello Hello Hello }

11. Extension functions

fun String.addExclamation(): String { return "$this!" } fun main() { val message = "Hello" println(message.addExclamation()) // Hello! }

12. Ví dụ thực tế

Tính BMI

fun calculateBMI(weight: Double, height: Double): Double { return weight / (height * height) } fun getBMICategory(bmi: Double): String = when { bmi < 18.5 -> "Gầy" bmi < 25.0 -> "Bình thường" bmi < 30.0 -> "Thừa cân" else -> "Béo phì" } fun main() { val weight = 70.0 // kg val height = 1.75 // m val bmi = calculateBMI(weight, height) val category = getBMICategory(bmi) println("BMI: %.2f".format(bmi)) println("Phân loại: $category") }

Kiểm tra số nguyên tố

fun isPrime(n: Int): Boolean { if (n < 2) return false for (i in 2..kotlin.math.sqrt(n.toDouble()).toInt()) { if (n % i == 0) return false } return true } fun main() { println(isPrime(17)) // true println(isPrime(20)) // false }

13. So sánh với Python

KotlinPython
fun name() { }def name():
fun sum(a: Int, b: Int): Intdef sum(a: int, b: int) -> int:
fun sum(a: Int, b: Int) = a + blambda a, b: a + b
vararg numbers: Int*numbers
Named argumentsNamed arguments

14. Best Practices

  1. Sử dụng single-expression cho hàm đơn giản
  2. Named arguments cho hàm nhiều tham số
  3. Tham số mặc định thay vì overloading
  4. Extension functions để mở rộng class
  5. Đặt tên hàm rõ ràng, động từ ở đầu: calculateTotal(), getUserInfo()

📝 Tóm tắt

  • fun keyword để định nghĩa hàm
  • Tham số: name: Type
  • Return type: : Type
  • Single-expression: = expression
  • Tham số mặc định và named arguments
  • vararg cho số lượng tham số không xác định
  • Extension functions để mở rộng class
  • Unit (mặc định), Nothing (throw exception)
Last updated on