==, equals, eq in scala

The equals method and == in scala check whether the values ​​are equal, and the eq method checks whether the reference is equal.

What is the difference between Scala's == and Java's

In Java, you can compare both primitive types and reference types . For primitive types , Java's == comparison compares by
value, as in Scala. However, for reference types , Java's == compares whether the reference is the same object (comparing memory addresses), that is, whether both variables point to the same object in the JVM heap. Scala also provides this
mechanism, named  eq . However, eq and its opposite, ne , apply only to objects that map directly to Java
.

In java, if you want to compare two objects by value, you must implement the equals and hashCode methods. In scala, a case class is provided for developers, and the equals and hashCode methods are implemented by default.

    case class Student(){}
    val stu1 = new Student()
    val stu2 = new Student()
    println(stu1 == stu2)
    println(stu1.eq(stu2))
    println(stu1.equals(stu2))
    val num1 = 10
    val num2 = 10
    println(num1 == num2)
//    println(num1.eq(num2)) eq只能比较引用类型
    println(num1.equals(num2))

 The output is as follows:

true
false
true
true
true

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324934922&siteId=291194637