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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With