Computer scienceProgramming languagesKotlinObject-oriented programmingObject-oriented programming usage

hashCode and equals

Car test

Report a typo

We have information about cars, and we have found out that it is not consistent in the equality tests. Please fix the indicated code to pass the test.

Fox example:

val car1 = "Ford-Mustang-1969"
val car2 = "Ford-Mustang-1969"
println(car1 == car2 && car1.hashCode() == car2.hashCode()) // true

Sample Input 1:

Ford-Mustang-1969 Ford-Mustang-1969

Sample Output 1:

true
Write a program in Kotlin
// Fix the code
class CarInfo(val brand: String, val model: String, val year: Int) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is CarInfo) return false
if (brand != other.brand) return false
if (model != other.model) return false
return year == other.year
}

override fun hashCode(): Int {
val result = brand.hashCode()
return result
}
}
___

Create a free account to access the full topic