Scala model-view-presenter, features

I am a fan of Martin Fowler (deprecated) presentation model presenter template. I am writing a Scala class class containing several button classes. I would like to include methods for setting the action properties of the buttons that the master calls. A typical piece of code looks like this:

private val aButton = new JButton
def setAButtonAction(action: Action): Unit = { aButton.setAction(action) }

This code is repeated for each button. If Java / Scala had a C preprocessor, I would create a macro to generate this code, given the name of the button (without lectures on the evil C preprocessor, please). This code is obviously very verbose and repetitive. Is there a better way to do this in Scala, possibly using traits?

Read lectures about scala.swing. I am looking for a generic template here.

+1
source share
1 answer

Scala is less about explicit setter and getter methods than java. Instead, use abstract fields to define a public interface. How about something like this:

trait ActionUser {
  def setAction(action:Action):Unit
}

trait Container {
  val aButton:ActionUser
}

trait ContainerImpl {
  val aButton = new JButton with ActionUser
}

Classes that work with Containerwill only be able to access setAction, and internal methods treat it like JButton.

One more note: C uses macros to reduce code duplication. Scala uses multiple trait inheritance to achieve the same.

+4
source

All Articles