method with angle brackets (<>)

不打扰是莪最后的温柔 提交于 2019-12-03 03:07:56

This response is not meant too serious and is just a proof that this can almost be achieved using some hacks.

class Vector(values: Int*) {
  val data = values.toArray
  def < (i:Int) = new {
    def `>_=`(x: Int) {
      data(i) = x
    }
    def > {
      println("value at "+ i +" is "+ data(i))
    }
  }
  override def toString = data.mkString("<", ", ", ">")
}

val v = new Vector(1, 2, 3)
println(v) // prints <1, 2, 3>
v<1> = 10
println(v) // prints <1, 10, 3>
v<1> // prints: value at 1 is 10

Using this class we can have a vector that uses <> instead of () for "read" and write access. The compiler (2.9.0.1) crashes if > returns a value. It might be a bug or a result of misusing >.

Edit: I was wrong; kassens's answer shows how to do it as you want.


It is not possible to implement a method that would be called when you write v<1> = 4 (except, maybe, if you write a compiler plugin?). However, something like this would be possible:

class Foo {
  def at(i: Int) = new Assigner(i)
  class Assigner(i: Int) {
    def :=(v: Int) = println("assigning " + v + " at index " + i)
  }
}

Then:

val f = new Foo
f at 4 := 6

With a little trickery you can actually get quite close to what you want.

object Foo {
  val a:Array[Int] = new Array(100)
  def <(i:Int) = new Updater(a, i)
}

class Updater(a:Array[Int], i:Int) {
  def update(x:Int) {
    a(i) = x
  }
  def >() = this
}

Foo<1>() = 123

I am not sure why Scala requires the () though. And yes, this is a bit of a hack...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!