Scala “object” examples

This article is a collection of Scala “object” examples. I put the word object in quotes there because it has at least two meanings in Scala. In the first meaning, just like Java, an object is an instance of a class.

In its second meaning, Scala has an object keyword, and using that keyword lets you do a variety of things, including a) creating a main method to launch your application, b) creating the equivalent of Java’s static methods, and also c) creating something called a companion object.

In the following Scala object examples I show how all of this works, but I don’t explain it in great detail. To learn more about Scala objects, please see the Scala Cookbook, where I share more examples and explain them in detail.

Objects and object instances

To cast an object instance, use asInstanceOf:

val recognizer = cm.lookup("recognizer").asInstanceOf[Recognizer]

Some REPL examples demonstrate this:

scala> val a = 10
a: Int = 10

scala> val b = a.asInstanceOf[Long]
b: Long = 10

scala> val c = a.asInstanceOf[Byte]
c: Byte = 10

The equivalent of Java’s .class (classOf)

If you’re coming from the Java world and want to use .class, you classOf instead:

val info = new DataLine.Info(classOf[TargetDataLine], null)

To create a launching point for your applications, you have two choices. First, you can define an object which extends App:

object Foo extends App {
  // your application begins here
}

Or you can define an object that contains a main method:

object Bar {
  def main(args: Array[String]) {
    // your application starts here
  }
}

Singleton objects

You create Singleton objects in Scala with the object keyword. You can’t create static methods in a Scala class, but you can create singleton objects in Scala with the object keyword, and methods defined in a singleton can be accessed like static methods in Java.

// create a singleton
object CashRegister {
  def open { println("opened") }
  def close { println("closed") }
}

// call the CashRegister methods just like static methods
object Main extends App {
  CashRegister.open
  CashRegister.close
}

Static methods in Scala

Here are more examples of “static” methods. First define the object:

import java.util.Calendar
import java.text.SimpleDateFormat

object DateUtils {

  // as "Wednesday, October 20"
  def getCurrentDate:String = getCurrentDateTime("EEEE, MMMM d")

  // as "6:20 p.m."
  def getCurrentTime: String = getCurrentDateTime("K:m aa")

  // a common function used by other date/time functions
  private def getCurrentDateTime(dateTimeFormat: String): String = {
    val dateFormat = new SimpleDateFormat(dateTimeFormat)
    val cal = Calendar.getInstance()
    dateFormat.format(cal.getTime())
  }

}

Now call them:

scala> DateUtils.getCurrentTime
res0: String = 10:13 AM

scala> DateUtils.getCurrentDate
res1: String = Friday, July 6

The Factory Method in Scala

You can implement the Factory Method in Scala by defining an apply method in a companion object. Just have the apply algorithm determine which specific type should be returned, and you can create new Animals like this:

val cat = new Animal("cat")
val dog = new Animal("dog")

To implement this behavior, create a parent trait:

trait Animal {
  def speak
}

In the same file, create a companion object, the classes that extend the base trait, and a suitable apply method:

object Animal {

  private class Dog extends Animal {
    override def speak { println("woof") }
  }
  
  private class Cat extends Animal {
    override def speak { println("meow") }
  }

  // my preferred factory method  
  def apply(s: String): Animal = {
    if (s == "dog") return new Dog
    else return new Cat
  }
}

Summary

As I mentioned, these are some of the examples you’ll find in the Scala Cookbook. Please see the Cookbook for more examples and details. You can find it at these links: