scala – 使用隐式类重写方法
发布时间:2020-12-16 09:00:18 所属栏目:安全 来源:网络整理
导读:我的目的是改变String中==方法的行为来调用equalsIgnoreCase. 这段代码 implicit class LowerCase(s: String) { override def ==(that: LowerCase) = that.equalsIgnoreCase(this)} 导致此错误 error: type mismatch; found : MyClass.LowerCase required: S
我的目的是改变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) 解决方法
如果类scala编译器中已有这样的方法,则不会搜索隐式转换.
请注意,您的实现无效,应该是: implicit class LowerCase(val s: String) { def ==(that: LowerCase) = that.s.equalsIgnoreCase(this.s) } 请注意,它仍然无用. 如果您想将其用作Map的键,您应该手动指定类型: 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”之类的变量,则应使用其他方法名称: implicit class LowerCase(val s: String) extends AnyVal { def ===(that: String) = s.equalsIgnoreCase(that) } scala> "a" === "A" res0: Boolean = true (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |