Can you return an assignable lvalue in Scala?

Posted by Alex R on Stack Overflow See other posts from Stack Overflow or by Alex R
Published on 2010-04-15T00:08:59Z Indexed on 2010/04/15 0:13 UTC
Read the original article Hit count: 587

Filed under:

(note, lvalue is actually a term from the C grammar, I don't know what it's called in Scala!)

Trying to learn Scala... this evening I'm working on an internal DSL for a dynamically scoped language that might resemble PHP syntax.

My REPL is: Welcome to Scala version 2.7.6.final (Java HotSpot(TM) Client VM, Java 1.6.0).

I have some made-up example code:


class $(any: Any) {
    def update(sym: Symbol, any: Any) { println("line 2 executed");}
    def ->(sym: Symbol) : $ = { println("line 1 executed"); return this  }
    def update(any: Any) { println("line 3 executed");}
}

The following works as expected:

scala> var a = new $(0)
a: $ = $@19238ad

scala> a('x) = "blah"
line 2 executed

On the other hand, why does the following not invoke the 1-parameter update method?

scala> a = 1
:6: error: type mismatch;
 found   : Int(1)
 required: $
       a = 1
           ^

Ultimately, I would like this to work:

a->'x = "blah"

Thanks

© Stack Overflow or respective owner

Related posts about scala