What is type of a singleton?


#1

When I define a singleton in Scala:

object MySingleton{}

then what is the type of this singleton?


#2

The type will be the (here slightly useless) “singleton type” called MySingleton.type.

In general any stable path (val, object, or combinations thereof) has a corresponding singleton type that can be retrieved in a similar way.


#3

You can ask the typechecker:

$ scala
Welcome to Scala 2.12.4 (Java HotSpot(TM) 64-Bit Server VM, Java 9.0.1).
Type in expressions for evaluation. Or try :help.

scala> object S {}
defined object S

scala> val s: Int = S
<console>:12: error: type mismatch;
 found   : S.type
 required: Int
       val s: Int = S
                    ^

#4

Or

$ scala
scala> :type object S
S.type