What is the rationale behind having companion objects in Scala?
Asked Answered
F

7

121

Is there a case where a companion object (singleton) for a class is needed? Why would I want to create a class, say Foo and also create a companion object for it?

Flue answered 4/3, 2009 at 8:46 Comment(2)
See also programmers.stackexchange.com/questions/179390/…Flex
See also https://mcmap.net/q/182748/-scala-companion-object-purpose-duplicate which is a good compilation of answers hereCollenecollet
S
92

The companion object basically provides a place where one can put "static-like" methods. Furthermore, a companion object, or companion module, has full access to the class members, including private ones.

Companion objects are great for encapsulating things like factory methods. Instead of having to have, for example, Foo and FooFactory everywhere, you can have a class with a companion object take on the factory responsibilities.

Speedwriting answered 4/3, 2009 at 22:54 Comment(0)
Y
68

Companion objects are useful for storing state and methods that are common to all instances of a class but they do not use static methods or fields. They use regular virtual methods which can be overridden through inheritance. Scala truly has nothing static. There are lots of ways you can use this but here's a simple example.

abstract class AnimalCounter
{
    var animals = 0

    def name: String

    def count()
    {
        animals += 1
        println("%d %ss created so far".format(animals, name))
    }
}

abstract class Animal
{
    def companion: AnimalCounter
    companion.count()
}

object Dog extends AnimalCounter
{
    val name = "dog"
}

class Dog extends Animal
{
    def companion = Dog
}

object Cat extends AnimalCounter
{
    val name = "cat"
}

class Cat extends Animal
{
    def companion = Cat
}

Which produces this output:

scala> new Dog
1 dogs created so far

scala> new Cat
1 cats created so far

scala> new Dog
2 dogs created so far

scala> new Cat
2 cats created so far
Yellowhammer answered 20/8, 2010 at 12:16 Comment(1)
similar illustration can be found also here: daily-scala.blogspot.sk/2009/09/companion-object.htmlAlanna
F
32

...and it's a good place to store static factory methods (not that DP) for accompanied classes. If you name those overloaded factory methods apply(/.../) you will be able to create/initialize you class

  1. without 'new' (not really that important)

  2. with different possible sets of parameters (compare to what Bloch writes in Effective Java about telescoping constructor)

  3. with the ability to to decide which derived class you want to create instead of the abstract (accompanied) one

Example code:

abstract class AbstractClass;
class RealThing(s: String) extends AbstractClass;
class AlternativeThing(i: Int) extends AbstractClass;
object AbstractClass {
  def apply(s: String) = {
    new RealThing(s)
  }
  def apply(i: Int) = {
    new AlternativeThing(i)
  }
}

// somewhere else you can
val vs = AbstractClass("asdf")  // gives you the RealThing wrapped over string
val vi = AbstractClass(123)  // gives you AlternativeThing wrapped over int

I wouldn't call the object/base class AbstractXxxxx because it doesn't looks bad: like creating something abstract. Give those names a real meaning. Consider using immutable, method less, case classes and seal the abstract base class.

Fafnir answered 10/3, 2009 at 12:55 Comment(2)
RealThing and AlternativeThing class should have a private constructor to force the user to use the AbstractClass has factory. class AlternativeThing private(i: Int) extends AbstractClassBlackout
@[Szymon Jachim] Scala abstract class does not support multiple inheritance. So why does the compiler allow it in your case?Hess
A
19

In addition to the things Saem said in his reply, the Scala compiler also looks for implicit conversions of types in the corresponding companion objects (of either the source or the target), so the conversions don't need to be imported.

About the reason for singleton objects in general Programming in Scala says:

As mentioned in Chapter 1, one way in which Scala is more object-oriented than Java is that classes in Scala cannot have static members. Instead, Scala has singleton objects (p. 65).

Allwein answered 4/3, 2009 at 23:12 Comment(0)
F
4

I always see companion objects as a bridge to write both functional and object oriented code in Scala. Many times we just need pure functions which take some input and provide a processing result. Putting those relevant functions in the companion object makes it easy to look up and use, for myself as well as some one building on top of my code.

Moreover, it is a language provided feature to write the singleton pattern without doing anything. This is especially useful when you need a singleton to encapsulate a delegator for the life of JVM. For example, writing a simple HTTP client library in Scala where you can encapsulate an underlying Java implementation based delegator and let consumers of your API live in pure world.

Footrace answered 11/5, 2015 at 13:13 Comment(0)
J
0

If you define class and object in same file with same name, they known as companion class and object. Scala don't have static as JAVA keyword, You can take as replacement of static with companion class and object in Scala.

For more detail information please check article class and object keyword in scala programming

Jonas answered 22/6, 2017 at 17:56 Comment(0)
M
-1

At first, it provides a clear separation of static vs non static methods methods.Also provide a simple way to create singleton class.

It also can inherit methods from other classes and/or traits, which cannot be done with Java static methods.and can be passed as a parameter.

Montespan answered 2/11, 2017 at 15:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.