Chapter 4. Utilizing object orientation

 

In this chapter

  • Object initialization
  • Abstract methods
  • Composition and Inheritance
  • Abstract interfaces
  • Type inference and public APIs

Scala is a rich object-oriented language. In Scala, every value is an object. Even operators are method calls against the class of an object. Scala offers mixin inheritance through the use of traits. Objects are core to everything in Scala, and understanding the details of how they work is important for using Scala.

Object, class, and traits are used to define public APIs for libraries. The initialization, comparison, and composition of objects are the bread and butter of Scala development. Initialization is important because of mixin inheritance and the way objects get instantiated in various locations. Comparing two objects for equality is critical and can be made trickier when inheritance gets in the mix. Finally, composition of functionality is how code reuse is accomplished, and Scala provides a few new ways to compose objects.

4.1. Limit code inside an object or trait’s body to initialization logic

In Scala, the code inside an object, trait or class’s body is the constructor.

A common starting point for most developers learning Scala is the standard “Hello, World” program. You’ll see many examples on the internet with the following code:

Listing 4.1. Poor Hello World! example in Scala

4.2. Provide empty implementations for abstract methods on traits

 
 
 
 

4.3. Composition can include inheritance

 
 

4.4. Promote abstract interface into its own trait

 
 
 

4.5. Provide return types in your public APIs

 
 
 

4.6. Summary

 
 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest