Jas
Jas

Reputation: 15093

scala mixin and single initialization

I want to use Metrics as a mixin.

So, I want to define multiple classes like this (pseudo-code):

class MyClass1 extends MyParent with MyMetricsHelper(myJMXMBeanServer)
class MyClass2 extends MyParent with MyMetricsHelper(myJMXMBeanServer) // repeat parameter bad
class MyClass3 extends MyParent with MyMetricsHelper(myJMXMBeanServer) // repeat parameter bad

as you see, when I call MyMetricsHelper, I pass in the parameters for myJMXMBeanServer so it would know to log to it.

However, I don't want to repeat myJMXMBeanServer in every class which mixes it in, because it's not nice to duplicate it.

Also, I do not want to have a different single point which will initialize the MyMetricsHelper because It does not look beautiful to me because I just want to mix it in and for it to work, I don't want to remember I have another point in code where I have to initialize it.

Any elegant way to achieve that?

Upvotes: 2

Views: 161

Answers (1)

Roland Ewald
Roland Ewald

Reputation: 4614

Traits are not allowed to have constructor parameters.

Instead, you could define a sub-trait that specified myJMXBeanServer for you (I'm not quite sure why you think initialization in one single place is bad --- it's either that or initialization in several places, which is what you have now):

class MyParent

trait MyMetricsHelper {
  val server: AnyRef // Replace by actual type, this means
                     // that we expect any impl. to initialize this field somehow
}

trait MyJMXMetricsHelper extends MyMetricsHelper {
  val server = "myJMXMBeanServer"
}

class MyClass1 extends MyParent with MyJMXMetricsHelper
class MyClass2 extends MyParent with MyJMXMetricsHelper
class MyClass3 extends MyParent with MyJMXMetricsHelper

Upvotes: 4

Related Questions