Search code examples
rubysorbet

Sorbet cannot resolve constant even though it is defined


Given:

# typed: true

module X
  class Y
  end
end

module X
  class X
    def y
      X::Y
    end
  end
end

Sorbet gives error :

editor.rb:6: Unable to resolve constant Y https://srb.help/5002
     6 |      X::Y

Why sorbet given error even though X::Y is defined?

Playground link


Solution

  • Because this is how constant lookup works in ruby. Roughly, it tries to resolve the name starting from innermost nesting. Therefore, in a your X::Y it resolves X to class X, which doesn't have Y.

    Use ::X::Y instead, to force lookup from top level.