What is a Singleton Type exactly?
Asked Answered
S

2

22

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

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

Sagitta answered 10/10, 2015 at 8:48 Comment(0)
M
18

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.

Misprint answered 10/10, 2015 at 9:45 Comment(5)
Perhaps you would be kind enough to give some examples as to the usefulness of this ?Sagitta
@ashy_32bit I've added some examples.Misprint
"checks that the matched object is the same as foo" -- did you mean "the same as Foo"?Pretentious
@VasyaNovikov Yes, fixed.Misprint
great answer, would be good to have an example for application 2. for completeness and precisionAlmazan
C
0

Put it in easy words, a singleton type is the type of a singleton object. That object becomes the only instance of such type, and such type's purpose is to provide language consistent syntax and type checking for that single object. The reason is that singleton types are so specific that type inference does not work for them, and hence it's the developer's duty to provide type for a singleton object. In other words you should provide type declaration where the compiler shall expect a singleton object, since compiler cannot infer types in such situations:

object X
val x: X.type = X

Main reason for a type system to exist is to check program correctness, hence any type construct such as X.type shall be seen in such perspective. To understand them, ask yourself "how should you instruct compiler to accept only value of X (and there is only one single of such value)?" For example instead of using X.type in the following snippet what else could be used?

case class example(x: X.type)

So we could say they are there to complement the type system of a language that made it so easy to adopt OOP's singleton pattern: "Singleton objects effectively implement the singleton pattern in Scala with no additional effort."

Cowles answered 20/10, 2023 at 14:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.