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

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

🎯 Mục tiêu: Hiểu cách sử dụng if-else trong Kotlin, đặc biệt là tính năng if as expression - điểm khác biệt lớn so với Java.


💡 Khái niệm

Trong Kotlin, if không chỉ là statement mà còn là expression - nghĩa là nó có thể trả về giá trị!

// Statement (như Java) if (x > 0) { println("Dương") } // Expression (Kotlin đặc biệt) - trả về giá trị val result = if (x > 0) "Dương" else "Không dương"

📝 Cú pháp cơ bản

if đơn giản

val age = 20 if (age >= 18) { println("Bạn đã đủ tuổi") }

if-else

val score = 75 if (score >= 50) { println("Đậu") } else { println("Rớt") }

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") }

⭐ if as Expression - Tính năng đặc biệt

Đây là điểm khác biệt quan trọng nhất của Kotlin so với Java:

val a = 10 val b = 20 // if trả về giá trị val max = if (a > b) a else b println(max) // 20 // Tương đương với ternary operator trong Java/C // Java: int max = (a > b) ? a : b;

Với blocks

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

[!TIP] Khi dùng if as expression, bắt buộc phải có else để đảm bảo luôn có giá trị trả về.


🔍 So sánh với Ternary Operator

Kotlin không có ternary operator ? :if-else expression đã đủ ngắn gọn:

// Kotlin val max = if (a > b) a else b // Java (ternary) // int max = a > b ? a : b; // Kotlin one-liner val status = if (isOnline) "Online" else "Offline" val displayName = if (name.isNotBlank()) name else "Guest"

🧩 Kết hợp với các operators

Elvis operator thay thế if-else cho null check

val name: String? = null // if-else val displayName = if (name != null) name else "Guest" // Elvis operator (ngắn gọn hơn) val displayName2 = name ?: "Guest"

Kết hợp với logical operators

val age = 25 val hasTicket = true val isVIP = false val canEnter = if (age >= 18 && hasTicket || isVIP) { "Được vào" } else { "Không được vào" }

📋 Nested if (if lồng nhau)

val age = 25 val hasID = true if (age >= 18) { if (hasID) { println("Được đăng ký") } else { println("Cần có CMND") } } else { println("Chưa đủ tuổi") } // Viết gọn hơn với && if (age >= 18 && hasID) { println("Được đăng ký") } else if (age >= 18) { println("Cần có CMND") } else { println("Chưa đủ tuổi") }

🛠️ Thực hành

Bài tập 1: Kiểm tra số chẵn/lẻ

fun main() { val number = 7 // TODO: In ra "Chẵn" hoặc "Lẻ" }

Lời giải:

fun main() { val number = 7 val result = if (number % 2 == 0) "Chẵn" else "Lẻ" println("$number là số $result") // 7 là số Lẻ }

Bài tập 2: Xếp loại học lực

fun main() { val score = 85.5 // TODO: Xếp loại theo thang điểm: // >= 90: Xuất sắc // >= 80: Giỏi // >= 70: Khá // >= 50: Trung bình // < 50: Yếu }

Lời giải:

fun main() { val score = 85.5 val grade = if (score >= 90) { "Xuất sắc" } else if (score >= 80) { "Giỏi" } else if (score >= 70) { "Khá" } else if (score >= 50) { "Trung bình" } else { "Yếu" } println("Điểm: $score → Xếp loại: $grade") }

Bài tập 3: Tính giá vé xem phim

fun main() { val age = 15 val isStudent = true val dayOfWeek = "Tuesday" // Thứ 3 giảm giá // TODO: Tính giá vé // Giá gốc: 100,000 // Dưới 12 tuổi: 50% // Sinh viên: 30% // Thứ 3: thêm 20% }

Lời giải:

fun main() { val age = 15 val isStudent = true val dayOfWeek = "Tuesday" val basePrice = 100_000 var discount = if (age < 12) { 0.5 } else if (isStudent) { 0.3 } else { 0.0 } // Cộng thêm giảm giá thứ 3 if (dayOfWeek == "Tuesday") { discount += 0.2 } val finalPrice = basePrice * (1 - discount) println("Giá gốc: ${"%,d".format(basePrice)} VNĐ") println("Giảm giá: ${(discount * 100).toInt()}%") println("Thành tiền: ${"%,.0f".format(finalPrice)} VNĐ") }

📱 Trong Android

// Xử lý visibility binding.errorText.visibility = if (hasError) View.VISIBLE else View.GONE // Set text color binding.statusText.setTextColor( if (isOnline) Color.GREEN else Color.RED ) // Conditional navigation val destination = if (isLoggedIn) { R.id.homeFragment } else { R.id.loginFragment } navController.navigate(destination) // Jetpack Compose @Composable fun Greeting(name: String?) { Text( text = if (name != null) "Hello, $name!" else "Hello, Guest!", color = if (name != null) Color.Blue else Color.Gray ) }

⚠️ Lưu ý quan trọng

[!WARNING] Khi dùng if-else as expression, phải có else:

// ❌ Lỗi compile - thiếu else val result = if (x > 0) "Positive" // ✅ Đúng val result = if (x > 0) "Positive" else "Non-positive"

[!TIP] Nên dùng when thay vì nhiều else if:

// Thay vì if (x == 1) ... else if (x == 2) ... else if (x == 3) ... // Dùng when when (x) { 1 -> ... 2 -> ... 3 -> ... else -> ... }

✅ Checklist - Tự kiểm tra

Sau bài học này, bạn có thể:

  • Sử dụng if, if-else, if-else if-else
  • Hiểu và sử dụng if as expression
  • Biết rằng Kotlin không có ternary operator ? :
  • Kết hợp if với logical operators
  • Tránh nested if bằng cách dùng && hoặc when

Tiếp theo: When Expression

Last updated on