mercredi 1 janvier 2020

Activate lazy variable by name

Let's say I have a case class with a lazy member

case class Person(name: String, surname: String) {
  lazy val initials: String = name(0) + "." + surname(0) + "."
}

And I have a universal function which converts it into Map

def getCCParams(cc: AnyRef) =
  cc.getClass.getDeclaredFields.map { f =>
    f.setAccessible(true)
    f.getName -> f.get(cc)
  }.toMap

now I create a person and get its values

val JohnSmith = Person("John", "Smith")
val res = getCCParams(JohnSmith)
println(res)

thus i get result

HashMap(initials -> null, name -> John, surname -> Smith)

initials equal null because it was not called. Is there any way to activate lazy value inside getCCParams function? The list of lazy members I can pass as a parameter

def getCCParams(cc: AnyRef, lazyMembers: List[String] = List("initials")) = ...

Thank you





Aucun commentaire:

Enregistrer un commentaire