user79074
user79074

Reputation: 5270

How to refer to a variable in an outer scope

If I have the following code:

trait MyTrait {
    val x: Int
}

def f(_x: Int) = new MyTrait {
    val x = _x
}

If I were to define my function as follows:

def f(x: Int) = new MyTrait {
    val x = x
}

This would be incorrect as val x is just referring to itself. Is there a way I can avoid having to use a different name for 'x' when I want to refer to something in the outer scope?

Upvotes: 1

Views: 820

Answers (3)

Alexey Romanov
Alexey Romanov

Reputation: 170745

You can, but only if the outer scope x is a member of enclosing type, not a method parameter or a local variable:

class MyOuter(val x: Int) {
  def f() = new MyTrait {
    val x = MyOuter.this.x
}

Upvotes: 5

Dima
Dima

Reputation: 40500

Well, in this particular case, you could write something like this:

 def f(x: Int) = {
    class Foo(val x: Int = x) extends MyTrait
    new Foo
  }

Not sure what exactly it makes better over just renaming x to y though ...

Upvotes: 0

P. Frolov
P. Frolov

Reputation: 876

Not really: in the scope of MyTrait, x refers to the field. However, you have the option to wrap parameter into some other name before you enter that scope:

def f(x: Int) = {
  val xn = x
  new MyTrait {
    val x = xn
  }
}

Upvotes: 3

Related Questions