Kotlin data class, singleton class

1. Data class: add the data keyword in front of the class

It will automatically generate equals(), hashCode(), toString() and other methods to reduce the amount of development code

data class Cellphone(val brand: String, val price: Double)
fun main(){
    
    
    val cellphone = Cellphone("Xiaomi", 4999.0)
    val cellphone2 = Cellphone("Huawei", 5999.0)
    println(cellphone)
    println(cellphone.hashCode())
    println(cellphone.toString())
    println("cellphone1 equals cellphone2: " + (cellphone == cellphone2))
}

insert image description here

2. Singleton class: object keyword

object Singleton {
    
    
    fun singletonTest() {
    
    
        println("singletonTest is called.")
    }
}

transfer:

fun main(){
    
    
    Singleton.singletonTest()
}

Kotlin automatically creates an instance of the Singleton class for us behind the scenes, and guarantees that there will only be one Singleton instance globally.

Guess you like

Origin blog.csdn.net/qq_41811862/article/details/120808829