Home Best Practices Difference between private and private?

Difference between private and private[this]?

Author

Date

Category

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Subscribe to our newsletter

To be updated with all the latest news, offers and special announcements.

Recent posts

OWASP Top 10 vulnerabilities and how Codacy helps to address them

In today’s modern, digitized world, security is more important than ever to respond to growing threats. Every web application comes with system vulnerabilities, and...

2020, It’s a wrap! 🎊

Looking back at 2020, it has been a year of change and innovation for Codacy. We became fully remote and will continue to be,...

Migrating to React: Typed named routes in react-router and Typescript

INTRODUCTION If you’re a regular user of Codacy, you might have noticed a few changes over the course of this year on some pages. We’re...

Introducing Pulse to help companies achieve elite engineering performance

At Codacy, we envision a future where everyone can impact the world by crafting complex software with confidence and focus at the speed of...

First QA Engineer in a Startup

This is the story of how I joined a startup as the first QA Engineer in the company.  My name is Bruno Medley, I'm a...