I get error message when tring to initialize array in initialize method. i`m new in crystal, but i think it should works..
https://crystal-lang.org/api/0.28.0/Array.html#new%28size%3AInt%2C%26block%3AInt32-%3ET%29-class-method
abstract class ClassA
@prev : UInt32
@current : UInt32
def initialize(@current : UInt32, @prev : UInt32)
@weight = Array.new(3) { |i| (i + 1) ** 2 } # not works**
weight2 = Array.new(3) { |i| (i + 1) ** 2 } # not works**
end
def some_func
weight3 = Array.new(3) { |i| (i + 1) ** 2 } # works !**
end
end
cast from Nil to Crystal::GenericInstanceType+ failed, at /crystal/src/compiler/crystal/types.cr:1651:20:1651 (TypeCastError)
from ???
from ???
from ???
from ???
from ???
from ???
from ???
from ???
from ???
from ???
from ???
from ???
from ???
And why i can`t initialize array in this way @w = uninitialized Float64[@current]?
It works only when i pass number @w = uninitialized Float64[5]
For a first problem: only the first line don't works. This is because compiler must deduce type of @weight instance variable, and apparently it's not clever enough to find correct generic specialzation. Use Array(Int32).new ....
Second problem - uninitialized Float64[5] creates StaticArray - they are quite different from usual Array and must have fixed size (because they are allocated on stack).
Duplicate of https://github.com/crystal-lang/crystal/issues/6390
Also, never user uninitialized and never recommend it, please.
As a workaround explicitly define the type of each instance variable.
Most helpful comment
Duplicate of https://github.com/crystal-lang/crystal/issues/6390
Also, never user uninitialized and never recommend it, please.