Zavior
Zavior

Reputation: 6462

What can I use scala.Singleton for?

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?

Upvotes: 8

Views: 148

Answers (1)

0__
0__

Reputation: 67330

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)

Upvotes: 1

Related Questions