Create an instance of a type parameter in macro

108 views
Skip to first unread message

Paul Butcher

unread,
Apr 22, 2012, 6:20:17 PM4/22/12
to scala-user
I want to create an instance of something passed as a type parameter to a macro. For instance, if I wanted to create a macro called "myNew" which does exactly what new does, I want:
def myNew[T] = macro myNewImpl[T]

def myNewImpl[T: c.TypeTag](c: Context) = reify(<[ new T ]>)
But all my attempts to work out what needs to go in the reify have failed :-(

--
paul.butcher->msgCount++

Snetterton, Castle Combe, Cadwell Park...
Who says I have a one track mind?

http://www.paulbutcher.com/
LinkedIn: http://www.linkedin.com/in/paulbutcher
MSN: pa...@paulbutcher.com
AIM: paulrabutcher
Skype: paulrabutcher

Miles Sabin

unread,
Apr 22, 2012, 6:40:44 PM4/22/12
to Paul Butcher, scala-user
On Sun, Apr 22, 2012 at 11:20 PM, Paul Butcher <pa...@paulbutcher.com> wrote:
> I want to create an instance of something passed as a type parameter to a
> macro. For instance, if I wanted to create a macro called "myNew" which does
> exactly what new does, I want:
>
> def myNew[T] = macro myNewImpl[T]
>
> def myNewImpl[T: c.TypeTag](c: Context) = reify(<[ new T ]>)
>
> But all my attempts to work out what needs to go in the reify have failed
> :-(

I think in this case you'll need to construct the tree by hand ... the
following works for me,

def myNew[T] = macro myNewImpl[T]

def myNewImpl[T: c.TypeTag](c: Context) : c.Expr[Any] = {
import c.mirror._
Apply(
Select(
New(TypeTree().setType(c.tag[T].tpe)),
newTermName("<init>")),
List())
}

Cheers,


Miles

--
Miles Sabin
tel: +44 7813 944 528
gtalk: mi...@milessabin.com
skype: milessabin
g+: http://www.milessabin.com
http://twitter.com/milessabin
http://underscoreconsulting.com
http://www.chuusai.com

Paul Butcher

unread,
Apr 23, 2012, 4:24:29 AM4/23/12
to Miles Sabin, scala-user
Cool - thanks Miles.

--
paul.butcher->msgCount++

Snetterton, Castle Combe, Cadwell Park...
Who says I have a one track mind?

http://www.paulbutcher.com/
LinkedIn: http://www.linkedin.com/in/paulbutcher
MSN: pa...@paulbutcher.com
AIM: paulrabutcher
Skype: paulrabutcher

Reply all
Reply to author
Forward
0 new messages