Over a million developers have joined DZone.

Scala Wonderland: Semicolons, Singletons and Companion Objects

· Java Zone

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

In Scala you may usually omit semicolon at the end of a statement. It is required if more statements are on a single line. Unfortunately there are cases when compiler doesn’t undrstand the code as you would expect. For example following is treated as two statements a and +b:

a + b

Solution is to use parenthesis (a + b).

Scala doesn’t have static members. It has singleton objects instead. Syntactically it looks like a class, except you use the keyword object. The main benefit is that an object can extend a class or mix in traits. On the other hand thay cannot take (constructor) parameters.

class Planet
object Earth extends Planet
object Sun extends Planet

When a singleton has the same name as a class, it’s called to be a companion object of that class. The class is denoted as the companion class. They both must be implemented in the same file. The beauty is that they can access each other’s private members. Typical usage is to have factory and helper methods in the companion object.

class Sheep(val name: String) {
  private var isBlack = false
}




object Sheep {
// Factory method #1
  def apply(name: String, isBlack: Boolean) = {
    val sheep = new Sheep(name)
    sheep.isBlack = isBlack
    sheep
  }




// Factory method #2
  def apply(name: String) = new Sheep(name)
}




Sheep("Dolly", true) // Calls factory method #1
Sheep("Daisy") // Calls factory method #2

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Published at DZone with permission of Rado Buranský, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}