Scala - 新的 vs 对象扩展 [英] Scala - new vs object extends

查看:32
本文介绍了Scala - 新的 vs 对象扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 new 运算符定义对象与通过扩展类定义独立对象之间有什么区别?

What is the difference between defining an object using the new operator vs defining a standalone object by extending the class?

更具体地说,给定类型 class GenericType { ... }val a = new GenericTypeobject a extends GenericType<有什么区别?/代码>?

More specifically, given the type class GenericType { ... }, what is the difference between val a = new GenericType and object a extends GenericType?

推荐答案

实际上,object 声明的初始化机制与字节码中的 new 相同.但是,有很多不同之处:

As a practical matter, object declarations are initialized with the same mechanism as new in the bytecode. However, there are quite a few differences:

  • object 作为单例——每个都属于一个只有一个实例存在的类;
  • object 被延迟初始化——它们只会在第一次被引用时被创建/初始化;
  • 一个object和一个class(或trait)同名是同伴;
  • object 上定义的方法在伴随的 class 上生成静态转发器;
  • object 的成员可以访问伴随 class 的私有成员;
  • 在搜索隐式时,相关*类或特征的伴随对象会被调查.
  • object as singletons -- each belongs to a class of which only one instance exists;
  • object is lazily initialized -- they'll only be created/initialized when first referred to;
  • an object and a class (or trait) of the same name are companions;
  • methods defined on object generate static forwarders on the companion class;
  • members of the object can access private members of the companion class;
  • when searching for implicits, companion objects of relevant* classes or traits are looked into.

这些只是我能想到的蝙蝠右侧的一些差异.可能还有其他人.

These are just some of the differences that I can think of right of the bat. There are probably others.

* 什么是相关"的类或特征是一个较长的故事——如果您感兴趣,可以在 Stack Overflow 上查找解释它的问题.如果找不到 scala 标签,请查看 wiki.

* What are the "relevant" classes or traits is a longer story -- look up questions on Stack Overflow that explain it if you are interested. Look at the wiki for the scala tag if you have trouble finding them.

这篇关于Scala - 新的 vs 对象扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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