My task is to find names of parameters of case class, for which there are default values.
In 2.9 I was using ScalaSigParser from scalap and did something similar to:
(...)
case x: MethodSymbol if x.name.startsWith("init$default$") => (...)
(...)
I was hoping that reflection in 2.10 would give me easier access to this kind of information.
Eventually I'd like to write a macro, which I would include in case class' companion object, which would automatically create a code for serialization/deserialization of that case class. To do that I need to know which parameters have default values.
Scala provides the ability to give parameters default values that can be used to allow a caller to omit those parameters. The parameter level has a default value so it is optional. On the last line, the argument "WARNING" overrides the default argument "INFO" .
It avoids Client confusion in passing Parameters to Method or Constructor calls. It improve the readability of the code.
A Scala Case Class is like a regular class, except it is good for modeling immutable data. It also serves useful in pattern matching, such a class has a default apply() method which handles object construction. A scala case class also has all vals, which means they are immutable.
An unapply method is generated, which lets you use case classes in more ways in match expressions. A copy method is generated in the class.
There is currently no way to do that, however I've just submitted a pull request (https://github.com/scala/scala/pull/1047) that adds TermSymbol.isDefaultParam
, which exposes the requested functionality. I hope it will make it into RC1 and 2.10.0-final.
scala> case class C(x: Int, y: Int = 2)
defined class C
scala> val ctor = typeOf[C].declaration(nme.CONSTRUCTOR).asMethod
ctor @ 39fe9830: reflect.runtime.universe.MethodSymbol = constructor C
scala> ctor.params.flatten filter (_.asTerm.isDefaultParam)
res0 @ 7ad2093b: List[reflect.runtime.universe.Symbol] = List(value y)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With