Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a Singleton Type exactly?

What is a singleton type? what are the applications, the implications ?

Examples are more than welcome and layman terms are even more welcome !

like image 211
Ashkan Kh. Nazary Avatar asked Oct 10 '15 08:10

Ashkan Kh. Nazary


People also ask

What is a singleton type?

A singleton type is a simple kind of data type made up of only one value. Singleton types are useful for representing named constants, such as the end-of-file marker value eof.

What's the point of a singleton?

The Singleton's purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields.

What does singleton mean in programming?

In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at a time. After the first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created.


1 Answers

If you think of a type as a set of values, the singleton type of a value x is the type which only contains this value ({x}). Usage examples:

  1. Pattern matching: case _: Foo.type checks that the matched object is the same as Foo using eq, where case Foo only checks that it's equal to Foo using equals.

  2. It's needed to write down the type of an object (as a type parameter, an argument, etc.):

    object A
    def method(): A.type = A
    
  3. To guarantee the return value of a method is the object it's called on (useful for method chaining, example from here):

    class A { def method1: this.type = { ...; this } }
    class B extends A { def method2: this.type = { ...; this } }
    

    You can now call new B.method1.method2, which you couldn't without this.type because method1 would return A.

like image 105
Alexey Romanov Avatar answered Sep 30 '22 20:09

Alexey Romanov