Named Scala self-adjusting shadow this "?"

Working through these messages , I thought that I understood that I myself understood, at least a few.

So, I created an example that did not live up to expectations:

scala> trait A { val v = "a" }
defined trait A

scala> trait B { this :A => ; var v = "" ; this.v = "b" }
<console>:6: error: reassignment to val
       trait B { this :A => ; var v = "" ; this.v = "b" }
                                                  ^

Self-tuning "this" of shadow B "this" - it looks weird, but it makes sense.

Then it would seem wise to give the car a different name. I did this and was pretty surprised:

scala> trait C { a :A => ; var v = "" ; this.v = "c" }
<console>:6: error: reassignment to val
       trait C { a :A => ; var v = "" ; this.v = "c" }
                                               ^

Is it still shaded ???

Changing the name of a local variable allows you to compile things, which makes sense:

scala> trait D { a :A => ; var w = "" ; this.w = a.v }
defined trait D

(And the proper type name can be additionally used to specify which "v" to use.)

Good. Does this mean the following should fail?

scala> trait E { this :A => ; var w = "" ; this.w = this.v }
defined trait E

AND? What is it?: - (

... ? "this", , .

, "this" "this" - ?

+3
2

self ( this, , : " B A [ยง5.1, Scala ]), .

:

trait A { val v = "a" }
trait B { this: A =>
  var v = "b"
}

new A with B {} // does not compile

<console>:9: error: overriding value v in trait A$class of type java.lang.String;
 variable v in trait B$class of type java.lang.String needs `override' modifier
   new A with B {}

, B, .

trait A { val v = "a" }
trait B { this:A => override val v = "b"  }

new A with B {}

A s v B. ( , new B with A {} , B .) , val, var - var.

, self-type . B, this , , . . B, B , .

trait B { this =>
  val v = "b"
  trait C {
    val v = "c"
    println(this.v)
  }
  new C {}
}
new B {}

// prints c

vs this:

trait B { self =>
  val v = "b"
  trait C {
    val v = "c"
    println(this.v)  // prints c
    println(self.v)  // prints b
  }
  new C {}
}
new B {}

( - this .)

+8

- . . ( - - : A {self: B = > ...} A B.) , self , , .

[...], self-type "this" "this"

, . . . , .

trait A {
  self1 =>

  trait B {
    self2 =>

    // Here unqualified this refers to B and not A, so "self1" is useful.
    // ...but not necessary, because A.this.xxx does the same thing.
  }
}
+4

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


All Articles