究竟什么是单例类型? [英] 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 !
推荐答案
如果你把一个类型看作一组值,一个值的单例类型 x
就是只包含这个的类型值 ({x}
).用法示例:
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:
模式匹配:
case _: Foo.type
使用eq
检查匹配的对象是否与Foo
相同,其中case Foo
仅使用equals
检查它是否等于Foo
.
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
.
需要写下object
的类型(作为类型参数、实参等):
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
为了保证方法的返回值是它被调用的对象(对于方法链很有用,例如 从这里):
class A { def method1: this.type = { ...; this } }
class B extends A { def method2: this.type = { ...; this } }
您现在可以调用 new B.method1.method2
,如果没有 this.type
,您将无法调用,因为 method1
将返回 A
.
You can now call new B.method1.method2
, which you couldn't without this.type
because method1
would return A
.
这篇关于究竟什么是单例类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!