how scala treat companion object? -
i'm new scala java background.
in java when want share field among different objects of class. declare field static.
class car { static no_of_tyres = 4; // implementation. public int getcarnooftyres(){ no_of_tyres; // although it's not practice use static without class name //but can directly access static member in same class . } } but in scala cannot declare static fields in class, need use object(companion object) that. in scala this,
class car { println(no_of_tyres); // scala doesn't let that. gives error println(car.no_of_tyres);// correct way. } object car { val no_of_tyres: int = 4; } i'm curious, how scala treat companion objects? different these 2 key-words (class , object) makes ? why scala not letting access no_of_tyres directly in class?
i'd reference answer same subject: what advantages of scala's companion objects vs static methods?
see section 4.3 of odersky's book programming in scala - chapter 4 - classes , objects
scala treats pure objects instances. in view java static member not part of instance, lives separate , different life.
with tricks of keyword object , syntactic sugar, can achieve same result maintaining stated principle: single instance of object instantiated , global access point instance provided.
Comments
Post a Comment