Kotlin 中擴充套件資料類


資料類是用於儲存應用程式資料的類。它就像我們在 Java 中用於儲存資料的 POJO 類。

在 Java 中,對於資料類,我們需要建立**getter** 和**setter** 方法來訪問該類的屬性。在 Kotlin 中,當一個類被宣告為資料類時,編譯器會自動建立一些訪問該類成員變數所需的輔助方法。編譯器將為建構函式引數建立**getter** 和**setter**、**hashCode()**、**equals()**、**toString()**、**copy()**。

為了使一個類在 Kotlin 中被視為資料類,需要滿足以下條件:

  • 主建構函式需要至少有一個引數。

  • 所有主建構函式引數都需要標記為**val** 或**var**。

  • 資料類不能是**抽象的**、**開放的**、**密封的**或**內部的**。

我們不能擴充套件資料類,但為了實現相同的功能,我們可以宣告一個**超類**並在**子類**中覆蓋屬性。

示例

在以下示例中,我們將建立兩個資料類“Student”和“Book”。我們還將建立一個抽象類“Resource”。在“Book”中,我們將覆蓋“Resource”類的屬性。

data class Student(val name: String, val age: Int)

fun main(args: Array) {
   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}")
   val b=Book(1L,"India","123222") // implementing abstract class
   println(b.location)
}

// declaring super class
abstract class Resource {
   abstract var id: Long
   abstract var location: String
}

// override the properties of the Resource 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

更新於: 2021-10-27

3K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告