Skip to Content
Kotlin📘 Ngôn ngữ KotlinCấu trúc rẽ nhánh (if-else)

Cấu trúc rẽ nhánh (if-else) trong Kotlin

1. If statement cơ bản

val age = 18 if (age >= 18) { println("Bạn đã trưởng thành") }

2. If-else

val age = 15 if (age >= 18) { println("Bạn đã trưởng thành") } else { println("Bạn chưa trưởng thành") }

3. If-else if-else

val score = 85 if (score >= 90) { println("Xuất sắc") } else if (score >= 80) { println("Giỏi") } else if (score >= 70) { println("Khá") } else if (score >= 50) { println("Trung bình") } else { println("Yếu") }

4. If expression (Trả về giá trị)

Đặc điểm quan trọng: Trong Kotlin, ifexpression (có giá trị trả về), không chỉ là statement như trong Python/Java:

val age = 20 val status = if (age >= 18) "Adult" else "Minor" println(status) // Adult // So sánh với Python // status = "Adult" if age >= 18 else "Minor"

4.1. If expression với block

val score = 85 val grade = if (score >= 80) { println("Excellent work!") "A" // Giá trị cuối cùng được trả về } else { println("Good effort") "B" }

5. Nested If (If lồng nhau)

val age = 25 val hasLicense = true if (age >= 18) { if (hasLicense) { println("Bạn có thể lái xe") } else { println("Bạn cần có bằng lái") } } else { println("Bạn chưa đủ tuổi") }

6. Logical Operators trong If

val age = 25 val hasLicense = true // AND (&&) if (age >= 18 && hasLicense) { println("Có thể lái xe") } // OR (||) if (age < 18 || !hasLicense) { println("Không thể lái xe") } // NOT (!) if (!(age < 18)) { println("Đã trưởng thành") }

7. Ranges trong If

val age = 25 if (age in 18..60) { println("Tuổi lao động") } if (age !in 0..17) { println("Không phải trẻ em") }

8. Null checks

val name: String? = "Alice" if (name != null) { println("Length: ${name.length}") } // Hoặc dùng safe call name?.let { println("Length: ${it.length}") }

9. So sánh với Python

KotlinPython
if (condition)if condition:
else ifelif
elseelse
val x = if (...) a else bx = a if ... else b

10. Ví dụ thực tế

fun main() { print("Nhập điểm: ") val score = readln().toIntOrNull() ?: 0 val grade = if (score >= 90) { "A" } else if (score >= 80) { "B" } else if (score >= 70) { "C" } else if (score >= 50) { "D" } else { "F" } val message = if (score >= 50) { "Đạt" } else { "Không đạt" } println("Điểm: $grade ($message)") }

📝 Tóm tắt

  • if trong Kotlin là expression, có thể trả về giá trị
  • Không cần dấu ngoặc đơn nhưng khuyến khích dùng
  • else if thay vì elif như Python
  • Có thể dùng in để kiểm tra range
  • Kết hợp tốt với null safety
Last updated on