Objects: Singletons, Part 2 (Scala 3 Video)
A second way to use objects in Scala is to put a collection of related functions inside the object. I refer to this as a utility object, although I don't know if there's any formal name in standard for this approach. Several examples of this approach are:
StringUtils
FileUtils
NetworkUtils
If you’re familiar with Java, the end result is similar to using static members in Java classes.
Example:
object StringUtils:
// return true if the string is null or empty
def isNullOrEmpty(s: String): Boolean =
if s==null || s.trim.equals("") then true else false
// convert "big belly burger" to "Big Belly Burger"
def capitalizeAllWords(s: String): String =
s.split(" ")
.map(_.capitalize)
.mkString(" ")
Usage examples:
StringUtils.isNullOrEmpty("")
// result: true
StringUtils.capitalizeAllWords("big belly burger")
// result: Big Belly Burger
Importing members from an object
When you were using methods from a utility object like this, another approach is to import them as shown in this example, and then you can just use the function names directly:
import StringUtils.*
isNullOrEmpty("")
capitalizeAllWords("big belly burger")
If you keep building on this concept, you can create collections of utility classes for all sorts of things:
object StringUtils:
def isNullOrEmpty(s: String): Boolean = ???
def capitalizeAllWords(s: String): String = ???
object FileUtils:
def readFile(filename: String): Try[Seq[String]] = ???
def writeFile(filename: String, contents: String): Try[Boolean] = ???
object NetworkUtils:
def getUrlContent(url: String): String = ???
object StockUtils:
def buildUrl(stockSymbol: String): String = ???
def getPrice(stockSymbol: String, html: String): String = ???
def getVolume(stockSymbol: String, html: String): String = ???
def getHigh(stockSymbol: String, html: String): String = ???
def getLow(stockSymbol: String, html: String): String = ???
object DateUtils:
def currentDate: String = ???
def currentTime: String = ???
Update: All of my new videos are now on
LearnScala.dev