我只是在互联网上的一些Scala教程,并注意到在一些示例中,一个对象被声明在示例的开始。
Scala中的 class 和对象之间的区别?
解决方案简要
您可以将 object 关键字视为创建 singleton 隐式定义的类的对象。
不那么简单考虑示例
扩展B与C { def f(x:Any):Any = ??? }从Scala视图中,声明
- 声明一个匿名(不可访问)类,扩展 B 和 C 和 创建此类名为 A 的单个实例。
- 启用 A(...)
- def unapply(...)允许创建自定义模式匹配提取器
- 如果附带同名的类,则该对象在解析隐藏参数
- declares an anonymous (inaccessible) class that extends both B and C, and
- creates a single instance of this class named A.
- 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
这意味着 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 BrieflyConsider the example
object A extends B with C { def f(x: Any): Any = ??? }From the Scala view, this declaration
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 objectThere exist some special methods that can be defined for objects:
更多推荐
Scala中对象和类之间的区别
发布评论