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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP