DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Message Routing in Akka
  • Universal Implementation of BFS, DFS, Dijkstra, and A-Star Algorithms
  • Queue in Data Structures and Algorithms
  • Writing an Interpreter: Implementation

Trending

  • How To Use ChatGPT API in Python for Your Real-Time Data
  • Five Free AI Tools for Programmers to 10X Their Productivity
  • Modular Software Architecture: Advantages and Disadvantages of Using Monolith, Microservices and Modular Monolith
  • A Complete Guide to Open-Source LLMs
  1. DZone
  2. Coding
  3. Languages
  4. Singleton Implementation in Scala

Singleton Implementation in Scala

Turns out Scala has a built-in implementation of a Singleton pattern that doesn't require too much work from a developer.

Ted Neward user avatar by
Ted Neward
·
Apr. 03, 16 · Tutorial
Like (6)
Save
Tweet
Share
19.15K Views

Join the DZone community and get the full member experience.

Join For Free

Implementation: Scala

Since Scala has some language syntactic sugar around “statics” that essentially turn all statics into a single object, it basically suggests that Scala has built-in implementation of Singleton without much more work to do:

class Product private(var state : Int) {
  def DoSomething() = {
    state += 1
    System.out.println("I did something for the " + this.state + " time")
  }
}

object Product {
  private val _instance = new Product(0)
  def instance() =
    _instance
}

Product.instance.DoSomething()
Product.instance.DoSomething()
Product.instance.DoSomething()

Here, we define a companion object in Scala (the “object” declaration) to hold the static instance of the Product, and return it when requested through the “instance()” definition.

In order to support the consequence that the Singleton should only ever have one instance at a time, we mark the primary constructor as “private”. Since the primary constructor is defined on the class-declaration line and is considered to be class-wide, this means that “private” appears before the primary constructor parameters in the very beginning of the class declaration.

Notice that Scala deliberately chooses to syntactically try to “hide” the differences in syntax between property, method, and field. As a result, despite that “instance()” is written using the method-style syntax, Scala will know how to resolve the field/property-style usage in the example.

Initialization note

For pedagogical purposes, we choose to demonstrate passing in the initial state for the Singleton, rather than having it initialized within the body of the class. This is simply to demonstrate how the private primary constructor syntax should look in Scala.

Lazy initialization

The earlier example uses the JVM’s static-initializer facilities to create the Product instance. (For the companion object above, Scala generates an auxiliary class, “Product$”, which holds a static initializer that immediately turns around and constructs an instance of “Product$”, which in turn immediately constructs the “Product” instance.) If the context demands that this initialization be deferred until the first time the “instance()” is requsted, the instance() definition must construct-on-demand, using traditional logic:

class Product private(var state : Int) {
  def DoSomething() = {
    state += 1
    System.out.println("I did something for the " + this.state + " time")
  }
}

object Product {
  private var _instance : Product = null
  def instance() = {
    if (_instance == null)
      _instance = new Product(0)
    _instance
  }
}

Product.instance.DoSomething()
Product.instance.DoSomething()
Product.instance.DoSomething()

A few syntactic changes are necessary in this implementation:

  • The instance field must be explicitly type-declared. This is because Scala’s type inference will make the best match it can, and in this case, since it is being initialized to null, it will assume it is of type Null, which then does not have a method “DoSomething()” declared on it.
  • The instance method must now be block-enclosed, since it is now more than one expression.
  • The instance field must be declared as “var” instead of “val”, since by definition we are changing its value after the companion object has been initialized.

Concurrency

Being a language that runs on the JVM, Scala has no stronger concurrency guarantees than Java, though it certainly prefers to take a different approach to the design of objects than Java has traditionally embraced (Scala prefers to build immutable objects over mutable ones). However, given that the Singleton often holds state, and that state tends to be immutable (after all, a constant global is often a compile-time constant and therefore no reason to use Singleton at all), it is generally safe to assume that any Singleton in Scala will need to have some kind of concurrency control around it just as any Java or other JVM-based language would.


Scala (programming language) Implementation

Published at DZone with permission of Ted Neward, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Message Routing in Akka
  • Universal Implementation of BFS, DFS, Dijkstra, and A-Star Algorithms
  • Queue in Data Structures and Algorithms
  • Writing an Interpreter: Implementation

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: