i not create getter :a, but this still compile and work. is this expected?
class A
@b : Int32
def initialize(@a : Int32 = 1)
@b = a + 1
end
end
p A.new 1
I think it's because when you do:
def initialize(@a : Int32)
Crystal actually does something like this:
def initialize(a : Int32)
@a = a
You can see this more easily by changing the example to instead set @a in the class body and omit it in the constructor.
I reopen, because the automatic rewrite shouldn't introduce a variable, it should be a temporary, inaccessible variable.
yes, this is bug is this case:
class A
def initialize(@a : Int32)
p a
end
def a
@a + 1
end
end
A.new(1)
output 1, but expected 2
We can simply document that @a = 1 in an initialize is re-written to a = @a. I don't think it's such big deal.
this is quite surprising, especially when you have a method with the same name (like in @kostya example) which is quite common. documenting won't help as much as what @ysbaddaden suggested - using a temporary, inaccessbile variable.
Depends upon #3413
Most helpful comment
I think it's because when you do:
Crystal actually does something like this:
You can see this more easily by changing the example to instead set
@ain the class body and omit it in the constructor.