Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala case class generated field value

I have an existing Scala application and it uses case classes which are then persisted in MongoDB. I need to introduce a new field to a case class but the value of it is derived from existing field.

For example, there is phone number and I want to add normalised phone number while keeping the original phone number. I'll update the existing records in MongoDB but I would need to add this normalisation feature to existing save and update code.

So, is there any nice shortcut in Scala to add a "hook" to a certain field of a case class? For example, in Java one could modify setter of the phone number.

Edit:

The solution in Christian's answer works fine alone but in my case I have defaults for fields (I think because of Salat...)

case class Person(name: String = "a", phone: Option[String] = None, normalizedPhone: Option[String] = None)

object Person {
  def apply(name: String, phone: Option[String]): Person = Person(name, phone, Some("xxx" + phone.getOrElse("")))
}

And if use something like: Person(phone = Some("s"))

I'll get: Person = Person(a,Some(s),None)

like image 810
Petteri H Avatar asked Sep 04 '25 17:09

Petteri H


1 Answers

You can define an apply method in the companion object:

case class Person(name: String, phone: String, normalizedPhone: String)

object Person {
  def apply(name: String, phone: String): Person =  Person(name, phone, "xxx" + phone)
}

Then, in the repl:

scala> Person("name", "phone")
res3: Person = Person(name,phone,xxxphone)
like image 69
Christian Avatar answered Sep 07 '25 18:09

Christian