Why init function for a class variable is executed twice?

The following code, when run, prints “inside init” twice, why?
https://play.crystal-lang.org/#/r/exio

class Test
  @@global : Int32
  @@global = init
 
  def self.init
    puts "inside init"
    1
  end
end

Output:

inside init
inside init
2 Likes

I don’t know why, but you can init it when declare it.

class Test
  @@global : Int32 = init

  def self.init
    puts "inside init"
    1
  end
end

in this case, it execute only once.

2 Likes

It seems that the compiler generates two calls to the var initializer Test::global:init, instead of just one.
This looks like a compiler bug.

Reminds me of Is there any optimization for constants? - #11 by straight-shoota