Nitin
Nitin

Reputation: 169

How to add common code in a scala Trait's method

trait T {
  def f(x: String): String
}

class A {
  override def f(x: String) = customMethodA(x.trim.toLowerCase)
} extends T

class B {
  override def f(x: String) = customMethodB(x.trim.toLowerCase)
} extends T 

In the example above, the parameter x goes through the same transformation in all the implementations of f. Is there a way to add the transformation in the trait T's f itself so it doesn't need to be repeated in A's and B's f?

Upvotes: 0

Views: 239

Answers (1)

You can make that method final and delegate its implementation to a protected abstract method like this:

trait T {
  final def f(x: String): String =
    fImpl(x.trim.toLowerCase)
  
  protected def fImpl(x: String): String
}

final class A extends T {
  override def fImpl(x: String): String =
    customMethodA(x)
}

final class B extends T  {
  override def fImpl(x: String): String =
    customMethodB(x)
}

Upvotes: 3

Related Questions