0

This constantly bugs me:

class Test(i: Int) {
  val this.i = i;
  val this.ii = i; // :(
}

I would like to declare all my vals/vars the same way, and I really don't understand why that this upsets the Scala compiler. Everywhere else this performs as expected except here.

  1. Is there a good reason why it won't let me punch in that this?
  2. Is there a better way/ a way around it/ a Scala way?
1
  • It looks like you are mixing JS (or maybe Ruby too) syntax with Scala. Commented Oct 13, 2012 at 11:36

2 Answers 2

9

Every variable you declare in that scope is going to be a field. So it warrants no special syntax.

class Test(_i: Int) {
  val i = _i
  val ii = i
}

Or even better:

class Test(val i: Int) {
  val ii = i
}

You can write it either way, depending on whether you are going for clearer and smaller code OR "consistent" code.

Sign up to request clarification or add additional context in comments.

Comments

3

The scala way is not to use this. Why do you use this in Java? To make it obvious that you are accessing a member of an instance and not a static member. This isn't necessary in Scala, since there are no static members and members of the companion object need to be prefixed with the companion object's name anyway.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.