• [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)
  • 相关阅读:
    (转)Mat, vector<point2f>,Iplimage等等常见类型转换
    人脸检测与识别的趋势和分析
    经典网络LeNet5看卷积神经网络各层的维度变化
    C++: int int& int * int**的区别、联系和用途
    c++从txt中读取数据,数据并不是一行路径(实用)
    Spyder常用快捷键
    批量读写变换图片(转)
    OpenCV属性页配置问题~
    视觉目标检测和识别之过去,现在及可能(2017.06.28)
    数据库---SQL Server
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13802897.html
Copyright © 2020-2023  润新知