首页 > 解决方案 > 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

标签: rubysorbet

解决方案


因为这就是 ruby​​ 中常量查找的工作方式。粗略地说,它尝试从最里面的嵌套开始解析名称。因此,在你的X::Y它解析Xclass X没有Y.

改为使用::X::Y强制从顶层查找。


推荐阅读