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:
-
Pattern matching:
case _: Foo.type
checks that the matched object is the same asFoo
usingeq
, wherecase Foo
only checks that it’s equal toFoo
usingequals
. -
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
-
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 withoutthis.type
becausemethod1
would returnA
.