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)
  • 相关阅读:
    17。3.12---re模块--正则表达式操作指南
    17.3.12---还有未整理的模块
    17.3.12---xmlrpclib模块
    17.3.12----math模块
    17.3.12--smtplib模块发送邮件__抄送,安装与下载
    17.3.12---logging日志模块level配置操作
    17.3.12---urlparse模块的URL下载
    17.3.12---socket
    17.3.12--urllib2模块
    SQLSERVER 中的共用表达式(CTE)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13802897.html
Copyright © 2011-2022 走看看