Why is an instance of the attribute created with default values ​​in Scala compilation error?

The error can be reproduced by compiling the following code:

object ReproducingMyError {

  trait MyTrait[X] {
    def someFunc: X
  }

  def f[X] = new MyTrait[X] {
    var x: X = _
    def someFunc: X = x
  }

}

2 error messages generated. Both point to

  def f[X] = new MyTrait[X] {
                 ^

Messages are similar:

Error: Parameter type in structural refinement may not refer to an abstract type defined outside that refinement

Error: Parameter type in structural refinement may not refer to a type member of that refinement

Why is this a compilation error?

+4
source share
1 answer

If you don't need to expose varfrom the outside (which I assume you are not doing this), then adding an explicit return type fixes the problem:

def f[X]: MyTrait[X] = new MyTrait[X] {
  var x: X = _
  def someFunc: X = x
}

Without an explicit type, the compiler displays problematic "structural refinement", that is, the type of which is as follows: MyTrait[X] { var x: X }.

- var private - , - , , .

def f[X] = new MyTrait[X] {
  private var x: X = _
  def someFunc: X = x
}
+2

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


All Articles