What is a Singleton Type for sure?

What is a singleton type? what applications, consequences?

Examples are more than welcome, and custom conditions are welcome!

+10
source share
1 answer

If you consider a type as a set of values, the singleton value type x is a type that contains only that value ( {x} ). Examples of using:

  1. Pattern matching: case _: Foo.type checks to see if the matching object matches Foo using eq , while case Foo checks to see if it matches Foo using equals .

  2. It was necessary to write the type object (as a type parameter, argument, etc.):

     object A def method(): A.type = A 
  3. For mutable objects, to guarantee the return value of a method is an object (useful for a chain of methods, an example here ):

     class A { def method1: this.type = { ...; this } } class B extends A { def method2: this.type = { ...; this } } 

    Now you can call new B.method1.method2 , which you could not have without this.type , because method1 will return. A

+9
source

Source: https://habr.com/ru/post/1233407/


All Articles