https://kotlinlang.org logo
#getting-started
Title
# getting-started
b

blue

08/15/2020, 11:16 PM
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

zsperske

08/15/2020, 11:24 PM
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

blue

08/15/2020, 11:25 PM
.equals
is working, but I thought
==
works same as
.equals
z

zsperske

08/15/2020, 11:26 PM
yes but in order for == to actually call your .equals method
it needs to use the signature I provided above
b

blue

08/15/2020, 11:27 PM
Ohk. Got it now
Thanks
z

zsperske

08/15/2020, 11:28 PM
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

blue

08/15/2020, 11:30 PM
and I need to learn Casting 🙂
z

zsperske

08/15/2020, 11:31 PM
as?
can be very useful but of course, always be careful with when you use casts
👍 1
n

nanodeath

08/16/2020, 3:35 PM
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

Michael de Kaste

08/17/2020, 9:55 AM
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
3 Views