現在、私はScalaを学習していますが、今は、オブジェクトを比較するためにOrdered traitsを理解しています。比較の私の現在の理解されている例次Scalaを理解する[]特性を比較するための特性
考えてみましょう、
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'を返したということだけです。比較で注文の通常の法律を確認するには、それをそのまま実装する必要があります。 –