user1893354
user1893354

Reputation: 5938

Scala - using string interpolation inside Trait containing unimplemented variable

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?

Upvotes: 2

Views: 145

Answers (1)

"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.

Upvotes: 3

Related Questions