了解Scala Ordered [] trait来比较引用

时间:2016-11-30 10:53:49

标签: scala traits

目前,我正在学习Scala,现在,我有一些混淆理解Ordered traits来比较对象。

考虑以下示例,这是我目前对比较的理解,

    -dontwarn org.xmlpull.v1.**
    -dontnote org.xmlpull.v1.**
    -dontnote org.apache.http.**
    -dontwarn java.awt.**
    -dontwarn org.postgresql.**
    -dontwarn com.google.**
    -dontwarn com.braintreepayments.**
    -dontwarn ch.qos.**
    -dontwarn retrofit.**
    -dontwarn ch.qos.**
    -dontwarn dagger.**
    -dontwarn com.flurry.**
    -dontwarn com.squareup.**
    -dontwarn okio.**

所以,我的问题是,如果类中有非构造函数字段会怎么样?例如,

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.

如果以上理解错误,请纠正我。

0 个答案:

没有答案