Skip to content
Advertisement

Scala Sealed trait def to val (How to set value?)

I’m kinda new to Scala and have been working on a piece of code that looks like this:

sealed trait Bank {
   def branch: Option[BranchName]
}
case object Bank {
  case class SomeBank(details: BankDetails)
  extends Bank {
    // NEED TO SET BRANCH HERE IN A VAL
    val branch = ???
  }
}

I’m kinda confused about how to set the branch variable which is defined as a def in the trait. When I debug I’d like to see branch as a property of the class so its be can be called as :SomeBank.branch because other services depend on branch as a property of the case class SomeBank.

The BranchName that is required as a return is another case class with bunch of details in it.

One hacky way of how I did it is by adding an extra parameter to case class:

case class SomeBank(details: BankDetails, setBranch: Option[BranchName]) 
extends Bank { val branch = setBranch }

However, this is bad because SomeBank basically has 2 properties that are duplicate i.e setBranch and branch are exactly the same. What would be the best way to do this so that I can just have branch set to what I want?

Advertisement

Answer

Case classes are good for modeling immutable data so keep in mind branch should be an immutable val under the case class SomeBank.

You can define branch directly (override val is optional):

case class SomeBank(
  details: BankDetails, 
  override val branch: Option[BranchName]
) extends Bank
Advertisement