Companion 类需要导入 Companion 对象方法和嵌套对象? [英] Companion class requires import of Companion object methods and nested objects?

查看:43
本文介绍了Companion 类需要导入 Companion 对象方法和嵌套对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看与 Akka 相关的类型安全激活器代码,以下结构引起了我的兴趣:

I am looking at Akka related typesafe activator code and the following construct intrigued me:

伴侣对象:

object MarkerActor {
  sealed trait MarkerMessage
  case object Stop extends MarkerMessage
   ..
  def objectMethod = print("hi from companion object")
}

伴生类:它导入伴生对象方法:

Companion class: it imports the companion object methods:

class MarkerActor extends Actor with ActorLogging {
    import MarkerActor._   // Comment this line to compare w or w/o import available

    objectMethod  // just to see if 'visible' within companion class

    override def receive = {
      case Stop => {

所以……这有点令人惊讶.为什么伴随类/对象之间没有特殊关系",允许类自动查看"对象方法?

So.. that is a bit surprising. Why is there not a "special relationship" between the companion class/object allowing the class to "see" the object methods automatically?

更新 我对此有点怀疑,因此继续注释掉import MarkerActor._",这导致 Companion 类中出现Symbol not found: Stop"错误.所以..确实需要导入.

Update I was a bit skeptical on this, and so went ahead and commented out the "import MarkerActor._" This resulted in "Symbol not found: Stop" errors in the Companion Class. So .. the import really is required.

推荐答案

几年前有一个关于是否将所有伴随对象成员隐式导入到它们的父类中的讨论.当时做出的决定(今天仍然有意义)是要求显式导入,因为添加额外的导入比删除不需要的导入更容易.这里是完整的讨论.

Several years ago there was a discussion on whether to implicitly import all companion object members into their parent classes. The decision made at the time, which still makes sense today, was to require an explicit import, since it is easier to add an additional import than to remove an undesired one. Here is the full discussion.

这篇关于Companion 类需要导入 Companion 对象方法和嵌套对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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