Currently this doesn't work in Crystal:
class Point
@x, @y : Int32
end
This doesn't work for structs either:
struct Point
x, y : Int32
end
Is this a good idea to support?
It'll be difficult to have getter
to support this, as getter x, y : Int32
would be recognized as 2 arguments: x
& y : Int32
, I don't know how the macro getter
could determine that x
is of type Int32
, and not an instance that don't have type defined here..
I'm not sure this would be benefical. In certain situations it would maybe be a bit better than writing it separately but in general you're probable better off writing each property destinctively.
:-1: to this from me too, it doesn't exactly feel like a common case, and just using multiple lines and a bit of duplication isn't really a massive issue.
@Qwerp-Derp you can use your own macros :smile:
macro int32(*args)
{% for arg in args %}
{{arg}} : Int32
{% end %}
end
class Foo
int32 @x, @y, @z
def initialize(@x, @y, @z)
end
end
foo = Foo.new(1,2,3)
pp foo # => #<Foo:0x... @x=1, @y=2, @z=3>
I'm also using some personal macros like static
:
macro static(m)
class_{{m}}
end
class MyClass
static property valor = 0
end
https://github.com/crystal-lang/crystal/issues/4689
I love Crystal macros :heart_eyes:
Maybe I'm using crystal macros too much :sweat_smile:
So, despite the two downvotes on @faustinoaq's post, he's right that this could easily be a macro, especially a more generic one:
macro decl(*args)
{% ty = args[-1] %}
{% vars = args[0...-1] + [ty.var] %}
{% for var in vars %}
{% if ty.value.is_a? Nop %}
{{ var }} : {{ ty.type }}
{% else %}
{{ var }} : {{ ty.type }} = {{ ty.value }}
{% end %}
{% end %}
end
class X
decl @a, @b : Int32 = 1
decl @c, @d : Int32
def initialize(@c, @d)
end
end
Oh sure it's possible but I don't think people should be introducing nonstandard macros into their projects when the alternative is so little extra typing.
I don't think people should overdo DRY in general. It often ends in the wrong abstraction.
Don't be lazy :-)
Can we close as won't fix?
Most helpful comment
Oh sure it's possible but I don't think people should be introducing nonstandard macros into their projects when the alternative is so little extra typing.
I don't think people should overdo DRY in general. It often ends in the wrong abstraction.