I'm trying to match a class constructor (from the set of alternatives) against a list of values that are retrieved from parsing some DSL. As these values are heterogeneous, I store them in an Array[Any]
.
I'm using the following piece of code to do so:
val myClassSymbol: ru.ClassSymbol = mirror.classSymbol(Class.forName(myClassName))
val cm: ru.ClassMirror = mirror.reflectClass(myClassSymbol)
val ctor = myClassSymbol.primaryConstructor.alternatives find { c =>
val signature: ru.Type = c.typeSignature
val constructorParams = signature.paramLists.flatten
val constructorParamValues: Seq[Any] = resultOfMyParsing
(constructorParamValues.size == constructorParams.size) && ((constructorParams zip constructorParamValues) forall ((pair: (ru.Symbol, Any)) => {
val sym = pair._1
var param = pair._2
??? // something to match the symbol with the value
}))
}
ctor map {c =>
val ctorm = cm.reflectConstructor(ctor.get.asMethod)
ctorm(resultOfMyParsing: _*)
} getOrElse {
throw new IllegalStateException(s"cannot find ctor for $constructorParamValues") // might be relace with some clever logic as a fallback
}
Has anyone an idea what to replace the ??? with? (or come up with a better/simpler solution altogether)
Many thanks in advance!
Aucun commentaire:
Enregistrer un commentaire