Search code examples
crystal-lang

Set attribute of type "Class" to define it as Int32, String, Float64


I have a class Container, which has an attribute type which stores the type of element stored in it:

class Container

  def initialize(@type = Class) 

  end

end

And I want to use it like this:

array = Container.new(Int32)
# or 
array = Container.new(String)

However, when running this I get: can't use Class as the type of instance variable @dtype of Crystalla::Ndarray, use a more specific type

How can I achieve this ? If I look at other languages and librairies like numpy, they do store a type in their ndarrays:

np.ndarray(shape=(2,2), dtype=float)

How can I achieve something similar in crystal ?

EDIT: dtype is a class itself in python, but it still seems to hold a type/class like I'm trying to achieve


Solution

  • I think you should use generics for that.

    class Container(T)
      @type : T.class
      @array : Array(T)
    
      def initialize
        @array = Array(T).new
        @type = T
    
        puts "Container elements type is #{@type}"
      end
    end
    
    array = Container(Int32).new
    

    Of course instance variable @type can be removed because you can always refer to T type in class definition.