📜  Kotlin-数据类

📅  最后修改于: 2020-12-30 07:04:21             🧑  作者: Mango


在本章中,我们将学习有关Kotlin编程语言的数据类的更多信息。只要一个类被标记为“数据”,就可以将其标记为数据类。这种类型的类可用于将基本数据分开。除此之外,它不提供任何其他功能。

所有数据类都需要具有一个主构造函数,并且所有主构造函数应至少具有一个参数。每当将一个类标记为数据时,我们都可以使用该数据类的某些内置函数,例如“ toString()”,“ hashCode()”等。任何数据类都不能具有诸如abstract和open或internal的修饰符。数据类也可以扩展到其他类。在下面的示例中,我们将创建一个数据类。

fun main(args: Array) {
   val book: Book = Book("Kotlin", "TutorialPoint.com", 5)
   println("Name of the Book is--"+book.name) // "Kotlin"
   println("Puclisher Name--"+book.publisher) // "TutorialPoint.com"
   println("Review of the book is--"+book.reviewScore) // 5
   book.reviewScore = 7
   println("Printing all the info all together--"+book.toString()) 
   //using inbuilt function of the data class 
   
   println("Example of the hashCode function--"+book.hashCode())
}

data class Book(val name: String, val publisher: String, var reviewScore: Int)

上面的代码将在浏览器中产生以下输出,在浏览器中,我们创建了一个数据类来保存一些数据,并从main函数访问了其所有数据成员。

Name of the Book is--"Kotlin"
Puclisher Name--"TutorialPoint.com"
Review of the book is--5
Printing all the info all together--(name-Kotlin, publisher-TutorialPoint.com, reviewScore-7)
Example of the hashCode function---1753517245