How does scala handle companion object?

I am new to ScalaJava with background.

In java, when we want to split any field between different objects of a class. we declare this field static.

class Car {
 static NO_Of_TYRES = 4;
 // some implementation.
public int getCarNoOftyres(){
       NO_Of_TYRES; // although it 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, for this we need to use object(companion object). In Scalawe will do so

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 wondering how does Scala handle companion objects? class and objectHow are these two keywords ( ) different ? why does Scala not allow us to access NO_Of_TYRESdirectly in the class?

+4
source share
3 answers

: Scala - ?

. 4.3 Scala - 4 -

Scala . java static - , .

object , : .

+2

Companion - ( ), singleton java :

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; }
}

:

Foo.getInstance().bar();

Scala

object Foo { 
    def bar: Int = 5 
}

Foo.bar

"" " "? - ( , , , ) , , , scala , - , (, , Java, Scala, )

+3

Scala, , , Java. , object. - Java, , .

class trait, /trait. , /. , /, . , , /.

+1
source

All Articles