Crystal: class variable bug

Created on 19 Sep 2018  路  3Comments  路  Source: crystal-lang/crystal

require "bit_array"

class A
  @@x = BitArray.new(1)
  @@x[0] = true

  def self.x_0
    return @@x[0]
  end
end

class B < A
end

b = B.new
puts b.class.x_0 # false
a = A.new
puts a.class.x_0 # true

question

Most helpful comment

Not a bug, just confusing. @@x in each class is a separate variable with separate values. @@x[0] is top-level code and runs only once. You want to write

require "bit_array"

class A
  @@x : BitArray = begin
    arry = BitArray.new(1)
    arry[0] = true
    arry
  end

  def self.x_0
    return @@x[0]
  end
end

class B < A
end

b = B.new
puts b.class.x_0 # false
a = A.new
puts a.class.x_0 # true

All 3 comments

Not a bug, just confusing. @@x in each class is a separate variable with separate values. @@x[0] is top-level code and runs only once. You want to write

require "bit_array"

class A
  @@x : BitArray = begin
    arry = BitArray.new(1)
    arry[0] = true
    arry
  end

  def self.x_0
    return @@x[0]
  end
end

class B < A
end

b = B.new
puts b.class.x_0 # false
a = A.new
puts a.class.x_0 # true

I'd like to experiment with removing the ability to run top-level code outside the :: namespace.

I guess we can actually close this?

Was this page helpful?
0 / 5 - 0 ratings