使用隐式类重写方法

时间:2013-12-20 08:19:27

标签: scala type-conversion

我的目的是更改==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)

1 个答案:

答案 0 :(得分:14)

如果类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