toString, equals और hashCode
In this page:
class ClassName(val field: Type) {
override def toString: String = s"ClassName($field)"
override def equals(other: Any): Boolean = other match {
case that: ClassName => field == that.field
case _ => false
}
override def hashCode: Int = field.hashCode
}
toString, equals, and hashCode
Default रूप से, एक plain class का toString Point@1a2b3c जैसा गैर-उपयोगी representation print करता है, क्योंकि Scala Java के default Object.toString को inherit करता है।
toString, equals, और hashCode को override करने से class को readable printing और सही value-based comparison/hashing मिलता है (जो Set/Map में उपयोग के लिए ज़रूरी है)। Case classes अपने आप तीनों generate करते हैं, यही वजह है कि इन्हें plain class में manually override करने के बजाय आमतौर पर प्राथमिकता दी जाती है।
उदाहरण: toString, equals, and hashCode
class Point(val x: Int, val y: Int) {
override def toString: String = s"Point($x, $y)"
override def equals(other: Any): Boolean = other match {
case that: Point => this.x == that.x && this.y == that.y
case _ => false
}
override def hashCode(): Int = (x, y).hashCode()
}
object Main extends App {
val p1 = new Point(1, 2)
val p2 = new Point(1, 2)
println(p1)
println(p1 == p2)
}
Login to try C/C++/Java/PHP code in the editor
hashCodeके बिनाequalsको override करना, जिससे बराबर objects के अलग hashes होते हैं और वे किसीSetयाMapमें गलत व्यवहार करते हैं।def equals(other: Point)लिखना, जो override करने के बजाय overload करता है क्योंकि parameterAnyहोना चाहिए।- उस स्थिति को handle न करना जहां
otherएकPointनहीं है, जिससेequalsएकClassCastExceptionफेंकता है।
- Classes में constructors, fields, और methods होते हैं, और access modifiers visibility control करते हैं।
- Companion objects संबंधित members रखते हैं।
- Case classes
toString,equals, औरhashCodeप्रदान करते हैं।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: