문제

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?

도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top