使用隐式类覆盖方法 [英] Using implicit class to override method
本文介绍了使用隐式类覆盖方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的目的是改变String
中==
方法的行为以调用equalsIgnoreCase
.
My intention is to change the behaviour of the ==
method in String
to call 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)
推荐答案
如果类中已经有这样的方法,scala 编译器不会搜索隐式转换.
In case there is already such method in class scala compiler would not search for implicit conversion.
注意你的实现是无效的,应该是:
Note that your implementation is invalid, it should be:
implicit class LowerCase(val s: String) {
def ==(that: LowerCase) = that.s.equalsIgnoreCase(this.s)
}
请注意,它仍然没有用.
Note that it's still useless.
如果您想将其用作 Map
的键,您应该手动指定类型:
In case you want to use it as Map
's key you should specify type manually:
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)
如果您想将此方法与这样的变量一起使用 "a" == "A"
您应该使用另一个方法名称:
If you want to use this method with variables like this "a" == "A"
you should use another method name:
implicit class LowerCase(val s: String) extends AnyVal {
def ===(that: String) = s.equalsIgnoreCase(that)
}
scala> "a" === "A"
res0: Boolean = true
这篇关于使用隐式类覆盖方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文