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?
import Car._
either at the file level or inside the class and useNO_OF_TYRES
– Daenyth