Square bracket operator with zero arguments


#1

In Scala we can overload the index operator `()` with zero arguments. This is used for instance for the `Signal` and `Var` classes in the Coursera course "Principles of Reactive Programming".

In Kotlin I’d like to have a shorter syntax for foo.value. It would be nice to be able to use foo[] to get and set foo.value.

data class Box<T>(var value: T) {   public fun get(): T { return this.value }   public fun set(value: T) { this.value = value } }

fun main(args: Array<String>) {
  val foo = Box(10)
  println(foo[])   // error: expecting an index element
  foo[] = 12           // error: expecting an index element
  println(foo[])   // error: expecting an index element
}

Relevant documentation: http://kotlinlang.org/docs/reference/operator-overloading.html


#2

Please use the same "()" operator (invoke) as in Scala.


#3

Thanks! Invoke with `()` looks even better. Is there a way to write `foo() = 12`?

data class Box<T>(var value: T) {
    public fun invoke(): T { return this.value }
    public fun invoke(value: T) { this.value = value }
    public fun set(value: T) { this.value = value }
}

fun main(args: Array<String>) {
  val foo = Box(10)

  // get
  println(foo())

  // set
  foo(12)
  foo() = 12 // error: variable expected
  foo set 12
}


The only way I found so far is to misuse compareTo() in order to write foo() &lt;= 12 instead of foo() = 12. One downside is, that I have to return Box&lt;T&gt; instead of T.

data class Box<T>(var value: T) {
    public fun invoke(): Box<T> { return this }
    public fun invoke(value: T) { this.value = value }
    public fun compareTo(value: T): Int { invoke(value); return 0 }
}

fun main(args: Array<String>) {
  val foo = Box(10)

  println(foo()) // Box(value=10)
  foo() <= 12
  println(foo()) // Box(value=12)
}


#4

No, there's no way to support "foo() = x"