Scala dynamic instantiation with default arguments

倾然丶 夕夏残阳落幕 提交于 2020-02-02 10:30:25

问题


Is there a way to dynamically instantiate a Scala case class having one or more default parameters specified?

I'm looking for the dynamic (reflection-based) equivalent of this:

case class Foo( name:String, age:Int = 21 )
val z = Foo("John") 

Right now if I try this I get an exception:

val const = Class.forName("Foo").getConstructors()(0)
val args = Array("John").asInstanceOf[Array[AnyRef]]
const.newInstance(args:_*)

If I add a value for age in my parameter array, no problem.


回答1:


Argument with default value are a compile-time thing. The compiler will feed in the default value for a call where the parameter is missing. No such thing with reflection, all the less with java reflection, which is not aware at all of default arguments.




回答2:


You can get default parameters as methods of object in runtime.

In case of constructor parameters - companion object methods (scala 2.9.3).

$ echo 'class Test(t: Int = 666)' > test.scala
$ scalac -Xprint:typer test.scala
...
<synthetic> def init$default$1: Int @scala.annotation.unchecked.uncheckedVariance = 666

You can't rely on the name of this method. (scala 2.10.1):

scala> Test.$lessinit$greater$default$1
res0: Int = 666

I don't know how to get default parameters for constructor, but in case of case class you could get apply method default parameters. See this answer.



来源:https://stackoverflow.com/questions/17003562/scala-dynamic-instantiation-with-default-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!