Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamical creating a new instance of a case class in scala

Given a reference to a case class companion object t and a sequence of parameter seq how can I invoke a new instance of the case class?

I can create a class when I type the number of the parameter by myself.

scala> case class B(n:String,a:Int,b:Int)
defined class B

scala> val t:AnyRef = B
t: AnyRef = B

scala> val m = t.getClass.getMethods.filter{m => m.getName == "apply"}.
    filterNot {_.getReturnType.getName == "java.lang.Object"}(0)
m: java.lang.reflect.Method = public B B$.apply(java.lang.String,int,int)

scala> m.invoke(t,"name",1:java.lang.Integer,2:java.lang.Integer)
res99: Object = B(name,1,2)

The problem I couldn't solve is to call invoke with a sequence of arguments like Seq("name",1:java.lang.Integer,2:java.lang.Integer). Any help how to do that is greatly appreciated.

I use scala 2.10.0.

like image 483
leo Avatar asked Apr 12 '13 15:04

leo


People also ask

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.

What is case class in scala syntax of case class?

What is Scala Case Class? 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.


1 Answers

Just found it out by myself (respectively have seen it over here https://stackoverflow.com/a/2060503/55070). It's

method.invoke(t,seq: _*)

Sometimes it really helps to just write it down ;-)

like image 194
leo Avatar answered Sep 23 '22 19:09

leo