Can you return the assigned lvalue to Scala?

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

Trying to get to know Scala ... tonight I am working on an internal DSL for a dynamic reach language that may resemble PHP syntax.

My REPL: Welcome to Scala version 2.7.6.final (Java Virtual Machine HotSpot (TM), Java 1.6.0).

I have code with ready-made 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 the following does not call the update method with 1 parameter?

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

When doing some trial and error, I found this syntactic curiosity:

scala> class A {def this_ = {print ("hello")}}
defined class A

scala> var a = new A
a: A = A @ 9aca82

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

scala> a.this_
: 7: error: value this_ is not a member of A
       a.this_
         ^

What is the meaning of overriding "this_" above? Where is he going?

Ultimately, I would like this to work:

a -> 'x = "blah"

thank

+3
source share
2
def this_= { print("hello") }

, , this_, { print("hello") }. this_=, (.. ).

:

scala> class A {
     |   private var _x = ""
     |   def x = _x
     |   def x_=(s: String) = _x = s.toUpperCase
     | }
defined class A

scala> new A
res0: A = A@1169fb2

scala> res0.x
res1: java.lang.String =

scala> res0.x = "abc"

scala> res0.x
res2: java.lang.String = ABC

, (id_=), , . - , .

, , lvalue Scala. :

id(key) = value // with update
id.key = value  // with key_=, as long as key also exists and is public
id += value     // or any other method containing "=" as part of its name

, :

scala> class A {
     |   private var _x = ""
     |   def :=(s: String) = _x = s.toUpperCase
     |   override def toString = "A("+_x+")"
     | }
defined class A

scala> val x = new A
x: A = A()

scala> x := "abc"

scala> x
res4: A = A(ABC)

=, , . , , Scala - , .

+8

, .

scala> case class Test (val x: Int)  
defined class Test

scala> implicit def testFromInt (x: Int) = new Test (x)
testFromInt: (Int)Test

scala> var a = new Test (3)
a: Test = Test(3)

scala> a = 10
a: Test = Test(10)

, , $ , /.

+1

Source: https://habr.com/ru/post/1741187/


All Articles