현재 스칼라를 배우고 있으며, 이제는 개체를 비교하기 위해 정렬 된 특성을 이해하고 있습니다. 비교의 나의 현재 이해하고있는 예를 다음스칼라 이해하기 [] 특성 비교를위한
고려,
Case I,
class Example(var n: Int) extends Ordered[Example] {
// ...
def compare(that: Example) =
(this.n) - (that.n)
}
var obj1 = new Example(12)
var obj2 = new Example(12)
obj1 compare obj2 //return 0 i.e. obj1 and obj2 are equal.
Case II,
class Example(var m: Int, var n: Int) extends Ordered[Example] {
// ...
def compare(that: Example) =
(this.m * this.n) - (that.m * that.n)
}
var obj1 = new Example(1, 2)
var obj2 = new Example(1, 2)
obj1 compare obj2 //return 0 i.e. obj1 and obj2 are equal.
Case III,
class Example(var name: String) extends Ordered[Example] {
// ...
def compare(that: Example) =
this.name compare that.name
}
var obj1 = new Example("abc")
var obj2 = new Example("abc)
obj1 compare obj2 //return 0 i.e. obj1 and obj2 are equal.
Case IV,
class Example(var name1: String, var name2: String) extends Ordered[Example] {
// ...
def compare(that: Example) =
(this.name1 + this.name2) compare (that.name1+that.name2)
}
var obj1 = new Example("abc","def")
var obj2 = new Example("abc","def")
obj1 compare obj2 //return 0 i.e. obj1 and obj2 are equal.
그래서, 내 질문입니다, 어떤 비 생성자 필드는 클래스가 있다면? 예 :
class Example(var n: Int) extends Ordered[Example] {
var someVar: String = "default";
// ...
def compare(that: Example) =
(this.n) - (that.n)
//do we also need to compare someVar???? otherwise, object will have different state right??
}
var obj1 = new Example(12)
obj1.someVar = "value 1"
var obj2 = new Example(12)
obj2.someVar = "another value 2"
obj1 compare obj2 //Again, return 0 i.e. obj1 and obj2 are equal.
위의 이해가 잘못 되었다면 수정하십시오.
'_ compare _ == 0'은 요소가 동일 함을 의미하지 않으며 사용 된 비교 함수가'0 '을 반환했다는 것을 의미합니다. 비교를 통해 주문의 일반적인 법칙을 확인하려면 해당 규칙을 그대로 구현해야합니다. –