Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can I use scala.Singleton for?

Tags:

scala

To clarify: I am NOT asking what I can use a Singleton design pattern for. The question is about largely undocumented trait provided in scala.

What is this trait for? The only concrete use case I could find so far was to limit a trait to objects only, as seen in this question: Restricting a trait to objects?

This question sheds some light on the issue Is scala.Singleton pure compiler fiction?, but clearly there was another use case as well!

Is there some obvious use that I can't think of, or is it just mainly compiler magicks?

like image 433
Zavior Avatar asked Aug 20 '14 15:08

Zavior


People also ask

What is singleton design pattern in Scala?

Scala Singleton Object Singleton object is an object which is declared by using object keyword instead by class. No object is required to call methods declared inside singleton object. In scala, there is no static concept. So scala creates a singleton object to provide entry point for your program execution.

What is the difference between singleton and companion design patterns?

A singleton object named the same as a class is called a companion object. Also a companion object must be defined inside the same source file as the class.


1 Answers

I think the question is answered by Martin Odersky's comment on the mailing list thread linked to from the linked question:

The type Singleton is essentially an encoding trick for existentials with values. I.e.

T forSome { val x: T }

is turned into

[x.type := X] T forSome { type X <: T with Singleton }

Singleton types are usually not used directly…

In other words, there is no intended use beyond guiding the typer phase of the compiler. The Scala Language Specification has this bit in §3.2.10, also §3.2.1 indicates that this trait might be used by the compiler to declare that a type is stable.


You can also see this with the following (Scala 2.11):

(new {}).isInstanceOf[Singleton]

<console>:54: warning: fruitless type test: a value of type AnyRef cannot also
                       be a Singleton
              (new {}).isInstanceOf[Singleton]
                                   ^
res27: Boolean = true

So you cannot even use that trait in a meaningful test.

(This is not a definite answer, just my observation)

like image 118
0__ Avatar answered Nov 06 '22 04:11

0__