2011-12-02 2 views
9
내가 코드 아래 시도했습니다

내가 스칼라는 Person의 각 인스턴스의 클래스 Room을 재정의하고 두 객실은 때로 믿을 이유가 있다고 발견 된 일부 분석 후스칼라에서 중첩 클래스의 패턴 일치 방법은 무엇입니까?

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 

을 (동등한 방법은 Programming in Scala 책 후 작성) 평등하다.

문제를 해결할 수있는 한 가지 방법은 클래스를 Person 클래스 외부에 배치하는 것이지만 가장 쉬운 방법은 아닙니다. (예를 들어, 클래스가 Person의 일부 매개 변수에 액세스해야하는 경우)

동일한 방법을 작성하려면 어떤 대안이 있습니까?

답변

15

문제는 두 개의 객실은 경로 의존적 유형의 인스턴스 있다는 것입니다 :이 일을 할

scala> :type p1.room 
p1.Room 

한 가지 방법 유형 선택, 즉 사용 Room을 참조한다 : 자신의 유형 p1.Roomp2.Room입니다 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