Is `==` and `equals` same in Kotlin? If so, can so...
# getting-started
b
Is
==
and
equals
same in Kotlin? If so, can someone help me why my program is returning
false
for below inputs
Copy code
John 19 0
John 19 22
Copy code
import java.util.*

data class Client(val name: String, val age: Int, val balance: Int) {
    fun equals(other: Client?): Boolean {
        return this.age == other?.age && this.name == other.name
    }
}

fun main(args: Array<String>) {
    val input = Scanner(System.`in`)

    val n = input.next()
    val a = input.nextInt()
    val b = input.nextInt()

    val nn = input.next()
    val aa = input.nextInt()
    val bb = input.nextInt()

    println(Client(n, a, b) == (Client(nn, aa, bb)))
}
also found this quote on Stackoverflow
In Kotlin 
==
 is compiled to 
equals
, whereas 
===
 is the equivalent of Java’s 
==
.
z
have you tried changing your .equals to
override fun equals(other: Any?): Boolean
i think you've just defined another method that isn't actually used
b
.equals
is working, but I thought
==
works same as
.equals
z
yes but in order for == to actually call your .equals method
it needs to use the signature I provided above
b
Ohk. Got it now
Thanks
z
np! the override keyword was required as well as using the correct method signature since .equals and == allow any value to be passed, not just another object of the same type
👍 2
b
and I need to learn Casting 🙂
z
as?
can be very useful but of course, always be careful with when you use casts
👍 1
n
IntelliJ can also Generate equals and hashcode for you, and it's usually a good idea to override both, per Effective Java's recommendation
m
I would btw not put relevant parameters in the primary constructor in this case. Data classes autogenerates an equals function for you, so you dont have to. In your case, I would solve it as followed:
Copy code
data class Client private constructor(val name: String, val age : Int){
    var balance: Int = 0
        private set
    
    constructor(name: String, age: Int, balance: Int) : this(name, age){
        this.balance = balance
    }
}
☝️ 1