Crystal: little unexpected behavior of variables in initialize

Created on 23 Apr 2017  路  6Comments  路  Source: crystal-lang/crystal

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
bug compiler

Most helpful comment

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.

All 6 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

will picture will  路  3Comments

costajob picture costajob  路  3Comments

cjgajard picture cjgajard  路  3Comments

nabeelomer picture nabeelomer  路  3Comments

ArthurZ picture ArthurZ  路  3Comments