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

การขยาย (Extend) Data Class ใน Kotlin: เทคนิคและข้อจำกัด

บทนำ

Data Class ใน Kotlin คือคลาสที่ออกแบบมาเพื่อเก็บข้อมูล (Data Holder) คล้ายกับ POJO ใน Java แต่ Kotlin สร้างโค้ด boilerplate ให้อัตโนมัติ: getters/setters, equals(), hashCode(), toString(), copy() และ componentN() functions

เงื่อนไขของ Data Class

  • Primary Constructor ต้องมีอย่างน้อย 1 พารามิเตอร์
  • พารามิเตอร์ทั้งหมดต้องมี val หรือ var
  • ไม่สามารถเป็น abstract, open, sealed, หรือ inner ได้

ข้อจำกัด: ไม่สามารถ Extend Data Class ได้โดยตรง

Data Class ถูกทำให้เป็น final โดยอัตโนมัติ (ไม่สามารถสืบทอดได้) เพื่อรักษาความสมบูรณ์ของ equals() และ hashCode()

วิธีแก้: ใช้ Abstract Class เป็น Base Class

สร้าง Abstract Class แล้วให้ Data Class Implement/Override Properties แทน

ตัวอย่างโค้ด

// Data Class ธรรมดา
data class Student(val name: String, val age: Int)

fun main(args: Array<String>) {
    val stu = Student("Student1", 29)
    val stu2 = Student("Student2", 30)
    println("Student1 Name is: ${stu.name}")
    println("Student1 Age is: ${stu.age}")
    println("Student2 Name is: ${stu2.name}")
    println("Student2 Age is: ${stu2.age}")

    // ใช้ Abstract Class เป็น Base
    val b = Book(1L, "India", "123222")
    println(b.location)
}

// Abstract Base Class
abstract class Resource {
    abstract var id: Long
    abstract var location: String
}

// Data Class Override Properties จาก Base Class
data class Book(
    override var id: Long = 0,
    override var location: String = "",
    var isbn: String
) : Resource()

ผลลัพธ์

Student1 Name is: Student1
Student1 Age is: 29
Student2 Name is: Student2
Student2 Age is: 30
India

สรุป

  • Data Class ไม่สามารถ open หรือถูก extend ได้
  • ใช้ abstract class หรือ interface เป็น Base แล้ว Override Properties ใน Data Class
  • Data Class ยังคงสร้าง equals(), hashCode(), toString(), copy() ให้อัตโนมัติครบถ้วน