zoukankan      html  css  js  c++  java
  • [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)
  • 相关阅读:
    IO—》字节流&字符流
    IO—》递归
    IO—》File类
    IDEA快速升级模块版本号
    redis使用Jackson2JsonRedisSerializer序列化问题
    git 创建管理多用户
    linux后台启动程序脚本实例
    linux 安装配置kafka脚本
    linux 安装配置zookeeper脚本
    linux安装配置JDK脚本
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13802897.html
Copyright © 2011-2022 走看看