Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how scala treat companion object?

Tags:

scala

I'm new to Scala with Java background.

In java when we want to share any field among different objects of class. we declare that field static.

class Car {
 static NO_Of_TYRES = 4;
 // some implementation.
public int getCarNoOftyres(){
       NO_Of_TYRES; // although it's not a good practice to use static without class name
                    //but we can directly access static member in same class  . 
  }


}

But in Scala we cannot declare static fields in class, we need to use object(companion object) for that. In scala we will do like this,

class Car {
 println(NO_Of_TYRES); // scala doesn't let us do that. gives error 
 println(Car.NO_Of_TYRES);// this is correct way. 

}

object Car {
 val NO_Of_TYRES: Int = 4;
}

I'm just curious, how scala treat companion objects? what different these two key-words (class and object) makes ? why does scala not letting us access NO_Of_TYRES directly in class?

like image 827
Muneeb Nasir Avatar asked Mar 16 '23 21:03

Muneeb Nasir


2 Answers

Companion objects are singleton class instances (and definitions), just to recall singleton in java is more or less:

class Foo {
    private Foo() { }
    /* boilerplate to prevent cloning */
    private static Foo instance = new Foo();
    public static Foo getInstance() { return instance; }

    public int bar() { return 5; }
}

and then to call method bar of this object:

Foo.getInstance().bar();

Scala removed all this boilerplate and lets you create equivalent thing with just

object Foo { 
    def bar: Int = 5 
}

and to call it you only need

Foo.bar

now what's the difference between 'object' and 'companion object'? It's actually quite simple - companion object (so the object defined in the same file as a class and having the same name) has access to it's related class private fields and methods, and that's probably why scala authors decided that it should reside in the same file - so that references to private fields are in the same file as their declarations (which I think is always the case both in Java and Scala, unless using reflection magic)

like image 122
Mariusz Sakowski Avatar answered Mar 26 '23 01:03

Mariusz Sakowski


I'd like to reference another answer about the same subject: What are the advantages of Scala's companion objects vs static methods?

See also Section 4.3 of Odersky's book Programming in Scala - Chapter 4 - Classes and Objects

Scala treats everything as pure objects with their instances. In this view a java static member is not part of any instance, it lives a separate and different life.

With the tricks of the keyword object and some syntactic sugar, you can achieve the same result but maintaining the stated principle: a single instance of that object is instantiated and a global access point for the instance is provided.

like image 27
ColOfAbRiX Avatar answered Mar 26 '23 03:03

ColOfAbRiX