10 Scope your code with Access Modifiers

 

After reading this lesson, you will be able to:

  • Make your values, variables, functions, and classes accessible only from their class
  • Limit your code accessibility to a class and its subclasses

In lesson 9, you have learned about packages. Protecting your code by limiting its accessibility is a good practice, especially when creating external modules for third parties. By doing so, you also reduce your code’s public entry points, making it easier to use. This approach also prevents external manipulations that could expose sensitive data or introduce undesired behavior in your code. In this lesson, you’ll learn about the Scala access modifiers, which are reserved keywords to change your code elements’ visibility. You should use them to protect and hide information that you should not expose to the public. You’ll use access modifiers to implement auxiliary functions accessible within their class in the capstone.

10.1  Public, the Default Access Modifier

Imagine you need to track the guests and the costs of a party. People registering for the event should be the only publicly accessible functionality. The following snippet provides a possible implementation:

10.2  Private

10.3  Protected

10.4  Which Access Level to use?

10.5  Summary

10.6  Answers to Quick Checks