Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
593 views
in Technique[技术] by (71.8m points)

scala - What is a Singleton Type exactly?

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...