Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check which parameters of case class have default value using scala reflection 2.10

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.

like image 309
Jarek Odzga Avatar asked Aug 03 '12 23:08

Jarek Odzga


People also ask

What is the function parameter with a default value in Scala?

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" .

What do default values and named parameters help you avoid in your code in Scala?

It avoids Client confusion in passing Parameters to Method or Constructor calls. It improve the readability of the code.

What is case class in Scala?

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.

What methods get generated when we declare a case class in Scala?

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.


1 Answers

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)
like image 85
Eugene Burmako Avatar answered Sep 18 '22 20:09

Eugene Burmako