[Kotlin] Data class

If we want to use Class to represent a piece of data such as Object, we can use Data class instead of normal class.

 

Difference: Data class has better toString() fun:

class Book (val title: String, val author: String, val publicationYear: Int, var price: Double) {}

data class DataBook(val title: String, val author: String, val publicationYear: Int, var price: Double) {}


fun main() {
    var book = Book("Super book", "John Doe", 2014, 99.09)
    var dataBook = DataBook("Super Book", "John Doe", 2014, 99.09)
    
    println(book) // Book@5451c3a8
    println(dataBook) // DataBook(title=Super Book, author=John Doe, publicationYear=2014, price=99.09)
}

Of course, we can override toString() fun in Book class, but DataClass already taken care for us.

 

Secondly, data class has better equals check:

class Book (val title: String, val author: String, val publicationYear: Int, var price: Double) {}

data class DataBook(val title: String, val author: String, val publicationYear: Int, var price: Double) {}


fun main() {
    var book = Book("Super book", "John Doe", 2014, 99.09)
    var book2 = Book("Super book", "John Doe", 2014, 99.09)
    var dataBook = DataBook("Super Book", "John Doe", 2014, 99.09)
    var dataBook2 = DataBook("Super Book", "John Doe", 2014, 99.09)
    
    println(book) // Book@5451c3a8
    println(dataBook) // DataBook(title=Super Book, author=John Doe, publicationYear=2014, price=99.09)

    println(book.equals(book2))  // false
    println(dataBook.equals(dataBook2)) // true
}

 

Useful copy() method:

var dataBook3 = dataBook.copy() // copy the same data
var dataBook4 = dataBook.copy(price=89) // copy with modification

 

Destructing:

var (title, author, year, price) = dataBook

 

hashSet: (no repeat items)

 var setBooks = hashSetOf(dataBook, dataBook3)

 

posted @ 2020-10-12 14:56  Zhentiw  阅读(158)  评论(0编辑  收藏  举报