Scala中对象和类之间的区别 [英] Difference between object and class in Scala
问题描述
我只是在互联网上的一些Scala教程,并注意到在一些示例中,一个对象被声明在示例的开始。
Scala中的 class
和对象
之间的区别?
简要
您可以将 object
关键字视为创建 singleton 隐式定义的类的对象。
不那么简单
考虑示例
扩展B与C {
def f(x:Any):Any = ???
}
从Scala视图中,声明
- 声明一个匿名(不可访问)类,扩展
B
和C
和
创建此类名为
A
的单个实例。 这意味着 A
可以传递给期望类型为 B的对象的函数
或 C
,并且可以使用 Af(...)调用方法
f
code>。
对象的额外功能
有一些可以为对象定义的特殊方法:
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
andC
, 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 ofA(...)
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屋!