具有默认参数的Scala动态实例化 [英] Scala dynamic instantiation with default arguments

查看:261
本文介绍了具有默认参数的Scala动态实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法动态实例化一个具有一个或多个默认参数的Scala案例类?

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.

推荐答案

具有默认值的参数是一个编译时的事情。编译器将为参数缺少的调用提供默认值。没有这样的事情与反思,所有更少与java反射,这是不知道所有的默认参数。

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.

这篇关于具有默认参数的Scala动态实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆