Crystal: Can't use self.new when argument isn't Type restricted

Created on 16 Dec 2019  路  3Comments  路  Source: crystal-lang/crystal

Broken example:

class Foo
  getter bar = [] of String

  def self.new(string)
    new(string.split(","))
  end

  def initialize(@bar)
  end
end

Foo.new("1,2,3")

Error: instance variable '@bar' of Foo must be Array(String), not String

Working example

class Foo
  getter bar = [] of String

  def self.new(string : String)
    new(string.split(","))
  end

  def initialize(@bar)
  end
end

Foo.new("1,2,3")

Most helpful comment

"I don't think so" to both questions.

All 3 comments

Invalid. In the first example the initialize will define a self.new that will override the other self.new.

Or said another way: if you do Foo.new("...") should the new or the initialize be called? It's not clear, so that's why it fails.

Ah, so since neither of them is type restricted, they'll end up overriding the generic 1 argument case.

Could this be implemented in the future, or perhaps reduced for this case? Since @bar already has an inline type restriction that it can pull from. Being unsure of the compiler internals, I'm not sure if the method can or cannot pull from the getter macro in that step.

Also, could the compiler keep both copies and only override once it goes through the "type restriction step".

"I don't think so" to both questions.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

oprypin picture oprypin  路  3Comments

RX14 picture RX14  路  3Comments

lbguilherme picture lbguilherme  路  3Comments

pbrusco picture pbrusco  路  3Comments

relonger picture relonger  路  3Comments