A code example

The aim of this example is to show how to create singleton instances in Scala and have an understanding of when exactly instances are created in Scala. We will look at a class called StringUtils, that provides different utility methods related to strings:

object StringUtils {  def countNumberOfSpaces(text: String): Int = text.split("\\s+").length - 1}

Using this class is then straightforward. Scala takes care of creating the object, thread safety, and so on:

object UtilsExample {  def main(args: Array[String]): Unit = {    val sentence = "Hello there! I am a utils example."    System.out.println(      s"The number of spaces in '$sentence' is: ${StringUtils.countNumberOfSpaces(sentence)}"    )  }}

The output from this program will be the following: ...

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.