What is the difference between object and class in Scala?

Marcin Krykowski

19th March 2021

In this article we will briefly describe the difference between object and class in Scala.

A class is a definition, a description. It defines a type in terms of methods and composition of other types.

An object is a singleton instance of a class. For every object in the code, an anonymous class is created, which inherits from whatever classes you declared object to implement.

Objects as static method holders

Quite often you will need an object to be host for some methods that shall be available without having to first instantiate an instance of some class. This use is closely related to static members in Java.

object MyObject { def addOne(n: Int): Int = n + 1 }

You can then call above method using MyObject.addOne(3).

If addOne were a member of some class A, then you would need to make an instance first:

class MyClass() { def addOne(n: Int): Int = n + 1 } val myClass = new MyClass() myClass.addOne(3)

You can see how redundant this is, as addOne does not require any instance-specific data.

Objects as a special named instance

You can also use the object itself as some special instance of a class or trait. When you do this, your object needs to extend some trait in order to become an instance of a subclass of it.

Consider the following code:

object A extends B with C { // some methods }

This declaration first declares an anonymous (inaccessible) class that extends both B and C, and instantiates a single instance of this class named A.

This means A can be passed to functions expecting objects of type B or C or B with C.

Additional features of objects

There also exist some special features of objects in Scala. I recommend to read the official documentation.

def apply(...) enables the usual method name-less syntax of A(...) def unapply(...) allows to create custom pattern matching extractors def copy(...) allows to create a copy of an instance with some parameters changed if accompanying a class of the same name, the object assumes a special role when resolving implicit parameters.

Summary

To sum up:

  • class C defines a class, just as in Java
  • object O creates a singleton object O as instance of some anonymous class. It might be used to hold static members that are not associated with instances of some class.
  • object O extends T makes the object O an instance of trait T. You can then pass O anywhere, a T is expected.
  • if there is a class C, then object C is the companion object of class C. Note that the companion object is not automatically an instance of C.

If you have still some concerns you can always reach out to the documentation for classes and objects.

Subscribe to receive the latest Scala jobs in your inbox

Receive a weekly overview of Scala jobs by subscribing to our mailing list

© 2024 ScalaJobs.com, All rights reserved.