The Crystal Programming Language Forum

Inheritance

I don’t understand why the compiler is complaining in the following example.

27| puts "a #{a.x} #{a.y} #{a.z}"
                       ^
Error: undefined method 'y' for Element (compile-time type is Element+)

Example

class Element
  property x : Int32 = 1
end

class Chip < Element
  property y : Int32 = 2
end

class ADC < Chip
  property z : Int32 = 3
end

# array of Element's
arr = [] of Element
arr << ADC.new
arr << Chip.new
arr << Element.new

a = arr[0]
puts "a #{a.class}"
puts "a #{a.x} #{a.y} #{a.z}"

See Virtual and abstract types - Crystal.

The compiler can’t guarantee that the first element of the array is an object that has a method called y because arrays are dynamic and the array is typed as Element, when not all implementations of it have a y method.

2 Likes