Scala:是否可以使方法“+”像这样工作:x + y = z?

时间:2012-09-03 23:34:12

标签: scala

我有一个图表,每个顶点连接到6个邻居。 在构建图形并进行连接声明时,我想使用如下语法:

1.    val vertex1, vertex2 = new Vertex
2.    val index = 3    // a number between 0 and 5
3.    vertex1 + index = vertex2

结果应该是vertex2 声明被指定为index - vertex1的邻居,相当于:

4.    vertex1.neighbors(index) = vertex2

在执行Vertex.+时,我想出了以下内容:

5.    def +(idx: Int) = neighbors(idx)
确实非常令人惊讶的是,导致第3行被我的IDE(IntelliJIdea,BTW)加下划线。 但是,第3行的编译是以下消息:

error: missing arguments for method + in class Vertex;
follow this method with `_' if you want to treat it as a partially applied function

接下来,我尝试使用提取器,但实际上,这似乎并不适合这种情况。

如果我想要达到的目标是否可行,是否有人有任何线索?

谢谢

2 个答案:

答案 0 :(得分:7)

您可以使用:=代替=来实现您的目标。看看这个说明repl会话:

scala> class X { def +(x:X) = x; def :=(x:X) = x }
defined class X

scala> val a = new X;
a: X = X@7d283b68

scala> val b = new X;
b: X = X@44a06d88

scala> val c = new X;
c: X = X@fb88599

scala> a + b := c
res8: X = X@fb88599

正如其中一条评论所述,自定义=需要两个参数,例如vertex1(i)=vertex2会被vertext.update(i,vertex2)取消,从而禁止您提出的确切语法。另一方面,:=是常规自定义运算符,a:=b将自行调整a.:=(b)

现在我们还有一个需要考虑的事情。优先级是否按照您的意图运行?根据{{​​3}},答案是肯定的。 +的优先级高于:=,因此最终以(a+b):=c的形式运行。

答案 1 :(得分:1)

不完全是你想要的,只是玩右关联性:

scala> class Vertex {
     |   val neighbors = new Array[Vertex](6)
     |   def :=< (n: Int) = (this, n)
     |   def >=: (conn: (Vertex, Int)) {
     |     val (that, n) = conn
     |     that.neighbors(n) = this
     |     this.neighbors((n+3)%6) = that
     |   }
     | }
defined class Vertex

scala> val a, b, c, d = new Vertex
a: Vertex = Vertex@c42aea
b: Vertex = Vertex@dd9f68
c: Vertex = Vertex@ca0c9
d: Vertex = Vertex@10fed2c

scala> a :=<0>=: b ; a :=<1>=: c ; d :=<5>=: a

scala> a.neighbors
res25: Array[Vertex] = Array(Vertex@dd9f68, Vertex@ca0c9, Vertex@10fed2c, null, null, null)