scala: defining a trait and referencing the corresponding companion object

inheritance, scala, traits

Solution

The solution I've found so far was to add a reference to the companion object in the class, so that every instance variable can get to the companion object of it's class

That way, I only have to override the method to get a reference to the companion object...

To do that I had to implement a ParentCompanion trait...

But I don't need to override callMyCompanion, or any other method that needs access to the companion object.

It all would be much simpler if I could get a reference of the companion object via reflection...

the code is something like this

:paste

trait ParentCompanion {
  def salute: String
}

class Parent {
  def callMyCompanion = print(companion.salute)
  def companion: ParentCompanion = Parent
}

object Parent extends ParentCompanion {
  def salute = "Hello from Parent companion object"
}

class Child extends Parent {
  override def companion = Child
}

object Child extends Companion {
  def salute = "Hello from Child companion object"
}

Problem

I'm trying to define a trait that uses the corresponding companion object, that is, the componion object of the class using the trait. for example, I have: ``` :paste class Parent { def callMyCompanion = print(Parent.salute) } object Parent { def salute = "Hello from Parent companion object" } class Child extends Parent { } object Child { def salute = "Hello from Child companion object" } ``` And then I create a parent object: ``` scala> val p = new Parent() p: Parent = Parent@1ecf669 scala> p.callMyCompanion Hello from Parent companion object ``` But with a child: ``` scala> val c = new Child() c: Child = Child@4fd986 scala> c.callMyCompanion Hello from Parent companion object ``` I'd like to get: Hello from Child companion object How can I achieve it??? -- edit to clarify Thanks for your responses, but in this case callMyCompanion is a dummy method I created just to explain myself, I'm trying to reuse the parent method without having to override it in every class that implements it... The solution I've found so far was to implement an instance method that uses the companion obejct...

Original source