2011-12-02 15 views
9
Ben kod aşağıda denedim

Ben Scala Person her örneği için sınıf Room yeniden tanımlıyor ve bu iki oda değiller nedeni olduğunu bulduğumuz bazı analiz sonraScala'da iç içe geçmiş bir sınıf nasıl düzenlenir?

class Person() { 
    class Room(r: Int, c: Int) { 
     val row = r 
     val col = c 

     override def hashCode: Int = 
      41 * (
       41 + row.hashCode 
      ) + col.hashCode 

     override def equals(other: Any) = 
      other match { 
       case that: Room => 
        (that canEqual this) && 
        this.row == that.row && 
        this.col == that.col 
       case _ => false 
      } 

     def canEqual(other: Any) = 
      other.isInstanceOf[Room] 
    } 

    val room = new Room(2,1) 
} 

val p1 = new Person() 
val p2 = new Person() 

println(p1.room == p2.room) 
>>> false 

(eşit yöntem Programming in Scala bukitaba yazılır) eşit değil. Sorunu çözmek için

Bir olasılık sınıfının Person dışında sınıfını koymak, ama bu en kolay ne zaman değil. (Örneğin sınıf Person bazı parametreler erişmeye varsa.)

eşit yöntem yazmak için ne gibi alternatifler vardır?

cevap

15

Sorun iki oda bir yol bağımlı tip örnekleri olmasıdır: bu işi yapmak için

scala> :type p1.room 
p1.Room 

bir yolu tipi seçimi, yani kullanarak Room başvurmak için olduğu: çeşitleri p1.Room ve p2.Room vardır Person#Room.

class Person() { 
    class Room(r: Int, c: Int) { 
     val row = r 
     val col = c 

     override def hashCode: Int = // omitted for brevity 

     override def equals(other: Any) = 
      other match { 
       case that: Person#Room => 
        (that canEqual this) && 
        this.row == that.row && 
        this.col == that.col 
       case _ => false 
      } 

     def canEqual(other: Any) = 
      other.isInstanceOf[Person#Room] 
    } 

    val room: Room = new Room(2,1) 
} 

val p1 = new Person() 
val p2 = new Person() 

scala> p1.room == p2.room 
res1: Boolean = true 
İlgili konular