2013-12-20 111 views
7

我的意圖是更改String中的==方法的行爲以調用equalsIgnoreCase使用隱式類別覆蓋方法

此代碼

implicit class LowerCase(s: String) { 
     override def ==(that: LowerCase) = that.equalsIgnoreCase(this) 
} 

導致此錯誤

error: type mismatch; 
found : MyClass.LowerCase 
required: String 
     override def ==(that: String) = that.equalsIgnoreCase(this) 
+0

你是什麼意思的「不工作」?你有錯誤嗎?它的行爲與你期望的不一樣嗎?你期望什麼,它在現實中做了什麼,它與你的期望有什麼不同? – Jesper

+0

是的,增加了編譯器錯誤信息 – hanxue

回答

12

在情況下已經存在於類Scala編譯器這樣的方法不會爲隱式轉換搜索。

注意你的代碼是無效的,它應該是:

implicit class LowerCase(val s: String) { 
     def ==(that: LowerCase) = that.s.equalsIgnoreCase(this.s) 
} 

注意,它仍然是無用的。

如果你想用它作爲Map的重點應指定手動鍵入:如果你想使用此方法,像這樣"a" == "A"你應該使用其他方法名稱變量

implicit class LowerCase(val s: String) { 
     // Use `equals`, not `==` 
     override def equals(that: Any) = that match { 
     case t: LowerCase => t.s.equalsIgnoreCase(this.s) 
     case _ => false 
     } 

    override def toString() = s 
} 

scala> Set[LowerCase]("A", "a", "b") 
res0: scala.collection.immutable.Set[LowerCase] = Set(A, b) 

implicit class LowerCase(val s: String) extends AnyVal { 
     def ===(that: String) = s.equalsIgnoreCase(that) 
} 

scala> "a" === "A" 
res0: Boolean = true 
+1

有沒有辦法隱式重寫一個類的方法,即不擴展和手動覆蓋超類的方法? – hanxue

+0

仍然存在錯誤:刪除'override',構造函數參數需要是'val'。但即使如此,它也不會工作,因爲你提到的(斯卡拉沒有理由搜索隱式轉換)。 – Jesper

+0

@Jesper:謝謝,修正。 – senia