使用隐式类重写方法

Hanxue

我的意图是更改call中==方法的行为StringequalsIgnoreCase

这段代码

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章