Scala - using string interpolation inside Trait containing unimplemented variable

Viewed 77

Say I have the following Trait

trait Feature{
     val name:String
     val tableName = s"${name}_table"
}

and a class that extends it

class Feature1 extends Feature{
     val name = "feature1"
}

but when I initialize the class and print tableName I get "null_table" rather than "feature1_table". I am trying to fully understand why that is. Is it because since tableName is technically implemented within the Trait it takes the null value of name before it can get instantiated by the extending class?

1 Answers

"is technically implemented within the Trait it takes the null value of name before it can get instantiated by the extending class" Yes.

This is the workaround.

trait Feature {
  def name: String
  final lazy val tableName = s"${name}_table"
}

final class Feature1 extends Feature {
  override final val name = "feature1"
}

Another alternative would be using a abstrac class instead of a trait.
Scala 3 will introduce trait parameters to properly fix this.

Related