当前位置:网站首页>Default methods for Scala sample classes

Default methods for Scala sample classes

2022-06-25 01:03:00 Jue Niu thunder plough hot blade

//  Demonstrates the default methods of the sample class 
object  The default method of the sample class  {
    

  case class Person(var name: String, var age: Int) {
    }

  def main(args: Array[String]): Unit = {
    
    // apply(): Create objects quickly , Omit new keyword 
    val p1 = Person(" Zhang San ", 18)

    // toString(): Output statement , Call this method by default 
    println(p1)

    // equals(): Let's go through == Compare whether the attribute values of two objects are the same in the form of 
    val p2 = Person(" Zhang San ", 18)
    println(p1 == p2)

    // hashCode(): Get the hash value of the object 
    //  The hash value of the same object must be the same , The hash values of different objects are generally different 
    println(p1.hashCode())
    println(p2.hashCode())
    println("-" * 20)
    //  special case : The content is different , The hash value is the same 
    println(" important ".hashCode)
    println(" conversation ".hashCode)

    // copy(): Let's build on existing objects , Quickly build a similar object 
    val p3 = p2.copy(age = 20)
    println(p3)
  }

}
原网站

版权声明
本文为[Jue Niu thunder plough hot blade]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202210544013830.html