如何在Scala中覆盖=运算符

时间:2013-09-21 12:12:14

标签: scala

有没有办法在Scala中的类中覆盖或重载=运算符,以隐式转换数据而不定义隐式方法?

例如:

class A{
    def =(str:String)={
       .........
    }
}
.........
val a=new A
a="TEST"

3 个答案:

答案 0 :(得分:6)

您无法覆盖Scala中的=,因为它是语言定义的运算符(如([<-)。

你唯一能做的就是使用update-method:

scala> :paste
// Entering paste mode (ctrl-D to finish)

class A {
  var data = Map.empty[Int, String]
  def update(i: Int, str: String) {
    data += i -> str
  }
  def apply(i: Int): String =
    data(i)
}

// Exiting paste mode, now interpreting.

defined class A

scala> val a = new A
a: A = A@77cb05b9

scala> a(5) = "hello"

scala> a(5)
res7: String = hello

但仍然无法忽略a(5) = "hello"中的括号,因为a = "hello"是重新定义值的语法。如果只指定更新方法,a() = "hello"

,则def update(str: String) {...}的最短表示法为{{1}}。

有关如何使用更新方法的更详细说明,请参阅this blog post

答案 1 :(得分:5)

根据Scala语言规范第1.1节,=是保留字。因此,您不能覆盖或超载它。

答案 2 :(得分:3)

您还可以使用Scala-Virtualized,您可以覆盖所有控制结构。这几乎肯定是矫枉过正,但存在选择。

相关问题