Scala中对象和类之间的区别 [英] Difference between object and class in Scala

查看:155
本文介绍了Scala中对象和类之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在互联网上的一些Scala教程,并注意到在一些示例中,一个对象被声明在示例的开始。



Scala中的 class 对象之间的区别?

解决方案

简要



您可以将 object 关键字视为创建 singleton 隐式定义的类的对象。



不那么简单



考虑示例

 扩展B与C {
def f(x:Any):Any = ???
}



从Scala视图中,声明




  • 声明一个匿名(不可访问)类,扩展 B C

  • 创建此类名为 A 的单个实例。

    这意味着 A 可以传递给期望类型为 B的对象的函数 C ,并且可以使用 Af(...)调用方法 f code>。



    对象的额外功能



    有一些可以为对象定义的特殊方法:




    • 启用 A(...)

    • def unapply(...)允许创建自定义模式匹配提取器

    • 如果附带同名的类,则该对象在解析隐藏参数


    I'm just going over some Scala tutorials on the Internet and have noticed in some examples an object is declared at the start of the example.

    What is the difference between class and object in Scala?

    解决方案

    Briefly

    You can think of the object keyword as creating a singleton object of a class that is defined implicitly.

    Not So Briefly

    Consider the example

    object A extends B with C {
      def f(x: Any): Any = ???
    }
    

    From the Scala view, this declaration

    • declares an anonymous (inaccessible) class that extends both B and C, and
    • creates a single instance of this class named A.

    This means A can be passed to functions expecting objects of type B or C, and method f can be called using A.f(...).

    Additional Features of object

    There exist some special methods that can be defined for objects:

    • def apply(...) enables the usual method name-less syntax of A(...)
    • def unapply(...) allows to create custom pattern matching extractors
    • if accompanying a class of the same name, the object assumes a special role when resolving implicit parameters

    这篇关于Scala中对象和类之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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