Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Companion class requires import of Companion object methods and nested objects?

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

Companion object:

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?

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.

like image 806
WestCoastProjects Avatar asked May 16 '14 21:05

WestCoastProjects


People also ask

What is use of companion object in Kotlin?

1. companion object is how you define static variables/methods in Kotlin. You are not supposed to create a new instance of Retrofit / ApiService each time you execute a request, however.

What is difference between object and companion object in Kotlin?

Object expressions are executed (and initialized) immediately, where they are used. Object declarations are initialized lazily, when accessed for the first time. A companion object is initialized when the corresponding class is loaded (resolved) that matches the semantics of a Java static initializer.

What is the use of companion object in Scala?

A companion object is an object that's declared in the same file as a class , and has the same name as the class. A companion object and its class can access each other's private members. A companion object's apply method lets you create new instances of a class without using the new keyword.

Can case class have companion object?

When you want to define some functionality related to a case class you have two possible ways to do this. The first one is to create functions directly in the case class. Note that in order to define a companion object for a class you have to set the same names for them and declare them in the same file.


1 Answers

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.

like image 117
Chris Avatar answered Sep 28 '22 05:09

Chris