Search code examples
tuplescrystal-lang

How to create a tuple using constructor inside macro in crystal lang


I am trying to create a empty tuple inside macro but getting error - Error: undefined macro method 'TypeNode#new'


{% empty_tuple = Tuple.new %}

Here is link to crystal play - https://play.crystal-lang.org/#/r/8mxf

If i can't do this way, please tell me if there is any alternative

Update 1

I am trying to initialize a class - cases are some class constructor has arguments and some has not

So i thought of using tuple with splat for argument passing.

Here is crystal play link of what i am trying to do - https://play.crystal-lang.org/#/r/8n4g

Update 2

You can create a tuple using direct syntax

args = {1}

but this won't work in case you want to create empty tuple because hash syntax is similar & compiler throws error for providing type for hash declaration.

So i thought about using constructor syntax - Tuple.new

but it didn't work either.


Solution

  • I was trying to create instance of many classes using macro & that's why i chooses this approach.

    As i was unable to create empty tuple in macro. I came up with a hack - what if i get args of some method which does not have any args which means it will be empty tuple right ?

    but it was not, it was an empty array

    And again i was stucked. So i used

    if else

    to solve this problem. Basically check if class needs to be initiated with args, then create a class & pass arguments in constructor else initiate class without any args.

    Hope this helps someone.