Yuhuan Jiang
Yuhuan Jiang

Reputation: 2726

Why is instantiating a trait with default values in Scala a 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 were generated. Both point to

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

The 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?

Upvotes: 4

Views: 1237

Answers (1)

ghik
ghik

Reputation: 10764

If you don't need to expose the var outside (which I assume you don't), then adding explicit return type fixes the problem:

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

Without explicit type ascription, the compiler will infer the problematic "structural refinement", i.e. a type that looks like this: MyTrait[X] { var x: X }.

Yet another way to fix this is to declare the var as private - this way it won't be visible by anyone outside and, thus - won't be included in the inferred refinement type.

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

Upvotes: 2

Related Questions