← Back to Scala Course | Chapter 7: OOP Basics | Lesson 7 of 7

toString, equals और hashCode

toString, equals, और hashCode तय करते हैं कि किसी object को text के रूप में कैसे दिखाया जाए, दो objects की तुलना कैसे हो, और उन्हें तेज़ lookups में कैसे फाइल किया जाए। इन्हें खुद define करने से आपके objects समझदारी से व्यवहार करते हैं।
Syntax
scala
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 करने के बजाय आमतौर पर प्राथमिकता दी जाती है।

Note: अगर आप equals को override करें, तो आपको hashCode भी override करना चाहिए ताकि दोनों consistent रहें -- या बस एक case class का उपयोग करें, जो दोनों को सही तरीके से handle करता है।

उदाहरण: toString, equals, and hashCode

markup
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)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. hashCode के बिना equals को override करना, जिससे बराबर objects के अलग hashes होते हैं और वे किसी Set या Map में गलत व्यवहार करते हैं।
  2. def equals(other: Point) लिखना, जो override करने के बजाय overload करता है क्योंकि parameter Any होना चाहिए।
  3. उस स्थिति को 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.