简体   繁体   中英

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 ie 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM