Azeli
Azeli

Reputation: 748

Meaning of the Singleton word in Scala

I have an understanding of what Singleton objects are, but perusing a library i came across something that confused me: mixing in Singleton

trait Foo[A <: Bar with Singleton] 

I cant seem to find info on what this means. A is a subtype of Bar-with-Singleton-access? What does mixing in Singleton provide?

Upvotes: 3

Views: 92

Answers (2)

Bruce Lowe
Bruce Lowe

Reputation: 6213

There is a related question here: Is scala.Singleton pure compiler fiction?

And here: Why do String literals conform to Scala Singleton

which might help understanding scala.Singleton

"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 } 

It's not something you would generally use yourself. Although you could use Singleton to to enforce a type of a Singleton as say a parameter to a method. e.g.

object X
class C

def foo[T<:Singleton](singleton: T): Unit = {
  print(singleton.getClass.getName)
}

foo(X)    //This would work, outputs X$

foo(new C)    //This would not work

Upvotes: 3

Alexey Romanov
Alexey Romanov

Reputation: 170859

Singleton is the special type which all objects inherit. So this means A can only be SomeObject.type, where SomeObject is an object extending Bar. Or Nothing, because it's unfortunately a subtype of anything at all.

Upvotes: 0

Related Questions