optional
optional

Reputation: 3350

Create a var/val of singleton class in scala

I have created a class as :

class Standalone(val str:String)
{
    Console println "Creating : "+this;
    override def toString()= " str : "+str;
}
object StandaloneFactory
{
    private val standalones= Map("red"-> new Standalone("Red"),"blue"-> new Standalone("Blue"),"green"-> new Standalone("green"));
    def getColor(color : String) = if(standalones.contains(color)) standalones(color) else null;
}

I know Object StandaloneFactory will have a single instance as StandaloneFactory. I just want to create a var/val of Standalonefactory so I tried to this :

object StandaloneMain
{
    def main(args:Array[String])
    {
        var stdFac:StandaloneFactory= StandaloneFactory;
        Console println stdFac;
        Console.println(StandaloneFactory.getColor("red")); 
    }
}

but this does not compile and give error as following : error: not found: type StandaloneFactory

Now as I change

var stdFac:StandaloneFactory= StandaloneFactory;

to

var stdFac:StandaloneFactory.type= StandaloneFactory;

or

var stdFac= StandaloneFactory;

Code compiles and run successfully . I think it is related with aliasing in scala. I am not getting what is happening . Please help me to understand this.

Thanks.

Upvotes: 0

Views: 848

Answers (1)

AmigoNico
AmigoNico

Reputation: 6852

As an object, StandaloneFactory is a value, not a type. It is the sole instance of some type whose name is not apparent to you, but is available as StandaloneFactory.type. The name of the type is generated, currently by adding a $ to the object name -- in this case StandaloneFactory$. After compiling you will see such a classfile.

You asked for a reference explaining that object StandaloneFactory creates a value StandaloneFactory rather than a type by that name. Please see the bottom of this page in the Scala language spec, where both a class and an object named Point are created, and it says

the class definition defines the name Point in the type name space, whereas the object definition defines a name in the term namespace.

The two namespaces are discussed here. The "type namespace" is used for symbols that refer to types, and the "term namespace" is used for symbols that refer to instances of types.

Just to be crystal clear here, when you say object StandaloneFactory you create a type (whose name is StandaloneFactory$, not StandaloneFactory) and a value StandaloneFactory (which points to the only instance of StandaloneFactory$). You might be surprised at first that value StandaloneFactory does not point to an instance of type StandaloneFactory, but if you know about companion objects and case classes you will realize that the companion object for a type is a completely different animal from the type; it has to have its own type.

Upvotes: 2

Related Questions