How to get the get the type of a subtype?

Hello,

In situations where a class inherits from another class, is it possible to figure out the type of the subtyped class?

# Parent class
class Element
  getter contents
  def initialize(@contents : Array(String), @line : Int32, @position : Int32)
  end
end

# Subtype of Element
class Paragraph < Element
end

# Subtype of Element
class H1 < Element
end

# Subtype of Element
class H2 < Element
end

elements = [] of Element

# Add some instances to an array
elements << H1.new ["Introduction"], 1, 1
elements << H2.new ["Sextion"], 1, 1
elements << Paragraph.new ["Paragraph"], 1, 1

# Cycle through the array and check the type of each element in the array.
elements.each do |el|
  puts typeof(el)
  puts el.contents
end

In the last section of the code, in my elements.each the call to typeof returns Element for each of the elements.

What I’m trying to do is differentiate which element of the array is a Paragraph, which is a H1 etc…

https://play.crystal-lang.org/#/r/6icp

Can use a case which under the hood is calling is_a? TYPE.

This is also where overloaded methods come in, where you would call the same method with el but the type restriction on the param makes it select the right method.

Also some docs that helped me with this.

https://crystal-lang.org/reference/syntax_and_semantics/virtual_and_abstract_types.html
https://crystal-lang.org/reference/syntax_and_semantics/is_a.html

1 Like

And there’s the class method, as in exp.class

1 Like

There we go! class is what i was looking for!

Thanks asterite