1

New Research Report - Exploring the 2024 State of Software Quality

Group 370
2

SAST, DAST, IAST, and RASP: Key Differences and How to Choose

Group 370
3

Spotlight Whitepaper by IDC on Importance of Automated Code Review Technologies

Group 370

Difference between private and private[this]?

In this article:
Subscribe to our blog:

When using private and private[this] do you know the difference?

When adding the scope to the private modifier (private[X]), it effectively behaves as a “up to” X, where X designates some enclosing package, class or singleton object.

For example, private[bar], where bar is a package means that every instance of every class belonging to package bar can access whichever member the modifier is restricting.

In the case of private[this], it means that the member is only accessible for each instance.
This becomes more clear in the following example:

class Foo(foo:Foo){  
  private[this] val i = 2
  println(this.i + foo.i)
}
error: value i is not a member of Foo
class Foo(foo:Foo){  
  private val i = 2
  println(this.i + foo.i)
}
defined class Foo

As you can see, the second Foo doesn’t have any problem since any instance can access the private val i. However for the first Foo there’s an error since each instance cannot see other instance’s i.

It’s a good practice to write private[this] since it imposes a bigger restriction.

Looking for a way to make sure you’re using private[this] every time? We enforce it on Codacy!

Enforceable today on Codacy

Edit: We just published an ebook: “The Ultimate Guide to Code Review” based on a survey of 680+ developers. Enjoy!

About Codacy

Codacy is used by thousands of developers to analyze billions of lines of code every day!

Getting started is easy – and free! Just use your  GitHub, Bitbucket or Google account to sign up.

GET STARTED

RELATED
BLOG POSTS

Open for business
The last couple of months have been good to us.
What Programming Languages need Code Reviews?
This is a blog post of our Code Reading Wednesdays from Codacy (http://www.codacy.com): we make code reviews easier and automatic. We launched Codacy...
Pulse end of Open Beta and new pricing
I’m excited to announce we’re introducing a new pricing model to our Pulse product.

Automate code
reviews on your commits and pull request

Group 13