如何在Scala中覆盖=运算符

Poo*_*oya 3 scala

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

例如 :

class A{
    def =(str:String)={
       .........
    }
}
.........
val a=new A
a="TEST"
Run Code Online (Sandbox Code Playgroud)

kir*_*uku 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
Run Code Online (Sandbox Code Playgroud)

但是仍然不可能省略括号a(5) = "hello"因为a = "hello"是重新定义值的语法.最简单的表示法是a() = "hello",当你只指定这样的update-method时:def update(str: String) {...}

有关如何使用update-method的更详细说明,请参阅此博客文章.


mik*_*łak 5

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