how scala treat companion object?

scala companion object
scala companion object access class fields
scala companion object apply
scala object type
scala companion object constructor
scala class vs object vs trait
scala trait companion object
scala case class companion object

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?

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.

Scala/Objects, An object with the same name as a class is called a companion object. Conversely, the class is the object's companion class. A companion class or object can  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

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)

Scala Singleton and Companion Objects, I'd like to reference another answer about the same subject: What are the advantages of Scala's companion objects vs static methods? Companion Objects. A companion object in Scala is an object that’s declared in the same file as a class, and has the same name as the class. For instance, when the following code is saved in a file named Pizza.scala, the Pizza object is considered to be a companion object to the Pizza class: This has several benefits.

Scala, as you pointed out, cannot have static variables or methods, as known in Java. Instead, there are singleton objects, which are declared with the keyword object. Calling a method in this objects is like calling a static method in Java, except you are calling the method on a singleton object instead.

If this object has the same name of a class or trait, it is called the companion object of the class/trait. A companion object must be defined inside the same source file as the class/trait. A companion object differs from other objects as it has access rights to the related class/trait that other objects do not. In particular it can access methods and fields that are private in the class/trait.

Scala Object - Scala Singleton & Scala Companion Object, Scala features to best practices [2]: companion object The apply method in a companion object is treated specially by the Scala compiler and  > Scala Tutorial – Traits, Companion Object, Factory Pattern Scala Tutorial - Traits, Companion Object, Factory Pattern By Nadim Bahadoor | Last updated: February 12, 2020 at 13:07 pm

Companion objects provide us with a means to associate functionality with a class without associating it with any instance of that class. They are commonly used to provide additional constructors

Singleton Objects | Tour of Scala, You're still doing Java/C#/JavaScript/Python/PHP and need a wind of change? I was like that 4 years ago. I changed then to the data  Singleton Object. Scala is more object oriented language than Java so, Scala does not contain any concept of static keyword. Instead of static keyword Scala has singleton object. A Singleton object is an object which defines a single object of a class. A singleton object provides an entry point to your program execution.

how scala treat companion object?, There is a method called “apply” in companion object that is treated specially by the Scala compiler, and it lets us create new instances of  Scala Companion Object. In scala, when you have a class with same name as singleton object, it is called companion class and the singleton object is called companion object. The companion class and its companion object both must be defined in the same source file.

Scala features to best practices [2]: companion object, The apply method in a companion object is treated specially by the Scala compiler and lets you create new instances of your class without  A Companion Object is defined using the object keyword and the name of the object should be identical to the class name. In addition, the companion object should define an apply() method which will be responsible for instantiating an instance of the given class.

Companion objects on waitingforcode.com, One of the language features available to us in Scala which I think is DZone > Java Zone > Scala: Companion Objects Using Okta means you won't have to write or maintain any login code or handle user passwords; nor  And then I create a parent object: scala> val p = new Parent() p: Parent = Parent@1ecf669 scala> p.callMyCompanion Hello from Parent companion object But with a child: scala> val c = new Child() c: Child = Child@4fd986 scala> c.callMyCompanion Hello from Parent companion object I'd like to get: Hello from Child companion object

Comments
  • You can import Car._ either at the file level or inside the class and use NO_OF_TYRES
  • as per my knowledge, Companaion Object must be in same file? still i need to import i don't think so? my question is, how scala treats keyword class and object?
  • It needs to be in the same file.
  • I think the best answer for you is programmers.stackexchange.com/questions/179390/… Please take a look
  • The most important reason is that you can always add new code to the system. If you were allowed to add a new companion object in a different compilation unit, then anybody could add a new companion object and break the class's encapsulation by accessing its privates. The requirement that both companions be in the same compilation unit ensures that encapsulation is preserved. Or, put another way: if you have access to the source file of the class, encapsulation is out the window anyway.