mercredi 27 février 2019

How can I obtain the default value of a constructor parameter for a non-case class?

class Person(name: String, age: Int, numThings: Option[Int] = Some(15))

I can use Scala reflection to obtain defaults on a case class like this:

   val companionType: Type = classSymbol.companion.typeSignature
   val companionObject = currentMirror.reflectModule(classSymbol.companion.asModule).instance
   val companionMirror = currentMirror.reflect(companionObject)
   val defaultValueAccessorMirror =
   if (member.typeSignature.typeSymbol.isClass) {
     val defaultValueAccessor = companionType.member(TermName("apply$default$" + (index + 1)))
     if (defaultValueAccessor.isMethod) {
       Some(companionMirror.reflectMethod(defaultValueAccessor.asMethod))
     } else {
       None
     }
   } else {
     None
   }

This obtains the method in the generated companion object that, when called, coughs up the default value. Sadly, a non-case class doesn't appear to have this facility.

How can I obtain the default value for Person.numThings in the example above using either Scala or Java reflection?





Aucun commentaire:

Enregistrer un commentaire