Skip to main content

Traits

Traits add new features to your Java class by providing default implementations you can then "import".

Basic explanation

Traits are essentially nothing more than Java interfaces. They provide default methods to the implementing class or interface. You can "import" traits via the implements statement in your class definition.

The difference between traits and normal Java interfaces are essentially that a trait adds features without forcing the implementing class to overwrite/implement the defined methods like normal interfaces would do.

After importing a trait you have access to the provided methods from the trait in your current scope.

Take a look at the following example for a better understanding:

A basic logging trait

Imagine you have a class that wants to log a message to the console:

MyClass.java
public class MyClass {
public void addNumbers() {
int sum = 1 + 2;
// that's tedious
// and where's the classname in front of the logging message?
System.out.printf("The sum is %d", sum);
}
}

And you have a trait to support the requested feature:

WithLogging.java
public interface WithLogging {
default void log(String format, Object ...args) {
System.out.print(getClass().getName() + ": ");
System.out.printf(format, args);
}
}

You can now implement the WithLogging by using the default implemented method log:

MyClass.java
public class MyClass implements WithLogging {
public void addNumbers() {
int sum = 1 + 2;
log("The sum is %d", sum);
}
}

Conventions

The name of a trait typically contains the prefix With and an action call describing what the trait provides to the implementing class or interface. For example:

  • WithLogging
  • WithEventBus
  • WithTiming
  • etc.

See also

Using traits in Verticles »/application/tutorials/using-traits-in-verticles/Writing your own traits »/application/guides/writing-your-own-traits/List of Telestion Core Verticle traits »https://javadoc.io/doc/de.wuespace.telestion/telestion-api/latest/de/wuespace/telestion/api/verticle/trait/package-summary.html