究竟什么是单​​例类型? [英] What is a Singleton Type exactly?

查看:51
本文介绍了究竟什么是单​​例类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是单例类型?有哪些应用和影响?

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:

  1. 模式匹配:case _: Foo.type 使用eq检查匹配的对象是否与Foo相同,其中case Foo 仅使用 equals 检查它是否等于 Foo.

  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.

需要写下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屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆