Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีตรวจสอบว่า lateinit Variable ถูก Initialize แล้วหรือยังใน Kotlin

ภาพรวม

lateinit var อนุญาตให้ประกาศตัวแปร Non-null โดยไม่ต้องกำหนดค่าทันที แต่หากเข้าถึงก่อน Initialize จะโยน UninitializedPropertyAccessException Kotlin มีวิธีตรวจสอบสถานะก่อนเข้าถึง

การตรวจสอบด้วย ::property.isInitialized

class Tutorial {
    lateinit var name: String

    fun checkInitialization() {
        // ตรวจสอบสถานะ
        println("Initialized? ${::name.isInitialized}") // false

        name = "www.tutorialspoint.com"

        println("Initialized? ${::name.isInitialized}") // true
        println("Value: $name")
    }
}

fun main() {
    Tutorial().checkInitialization()
}

ผลลัพธ์

Initialized? false
Initialized? true
Value: www.tutorialspoint.com

การใช้งานจริง: ป้องกัน Exception

class UserProfile {
    lateinit var username: String
    lateinit var email: String

    fun displayProfile() {
        // ตรวจสอบก่อนใช้งาน
        if (::username.isInitialized && ::email.isInitialized) {
            println("User: $username ($email)")
        } else {
            println("Profile not fully loaded")
        }
    }

    fun loadFromServer(data: Map<String, String>) {
        username = data["username"] ?: ""
        email = data["email"] ?: ""
    }
}

ข้อจำกัดของ isInitialized

  • ใช้ได้เฉพาะ Property ใน Class เดียวกัน (Same class)
  • ไม่ใช้ได้กับ Property ของ Object อื่น: otherObj::prop.isInitialized ❌
  • ไม่ใช้ได้กับ Local Variable ใน Function
  • สำหรับ Property ใน Superclass ต้องใช้ this::property.isInitialized

ตัวอย่างข้อผิดพลาดที่พบบ่อย

class Example {
    lateinit var value: String

    fun wrongCheck(other: Example) {
        // ❌ Error: Cannot check initialization status of property in other instance
        // println(other::value.isInitialized)
    }

    fun correctCheck() {
        // ✅ OK: Check own property
        println(this::value.isInitialized)
    }
}

Best Practice

  1. ใช้ isInitialized ตรวจสอบก่อนเข้าถึงใน Logic ที่ไม่แน่ใจ
  2. ห่อหุ้มในฟังก์ชัน helper หากใช้บ่อย:
    fun <T> LateinitProperty<T>.getOrNull(): T? = if (isInitialized) get() else null
  3. พิจารณาใช้ by lazy หรือ Delegates.notNull() แทน หากเหมาะสมกว่า

Delegates.notNull() - ทางเลือกอื่น

import kotlin.properties.Delegates

class Example {
    var name: String by Delegates.notNull()

    fun test() {
        // name = "Hello" // ต้อง set ก่อน get
        // println(name) // โยน IllegalStateException ถ้ายังไม่ set
    }
}

Delegates.notNull() ใช้กับ var ได้ รองรับ Nullable Type และโยน Exception ที่ชัดเจนกว่า (IllegalStateException พร้อมข้อความ "Property should be initialized before get")