为什么 crystal 的类型推断不能按预期在 类 上工作?

Why doesn't crystal's type inference work on classes as expected?

为什么我可以在Crystal中定义一个方法:

def foo(bar): String
  bar.to_json
end

foo({"x" => 1, "y" => 2})

但是这种类型推断不适用于 类:

class Foo
  def initialize(bar)
    @bar = bar
  end

  def foo: String
    @bar.to_json
  end
end


Foo.new({"x" => 1, "y" => 2}).foo

最后是

Error: can't infer the type of instance variable '@bar' of Foo

关于 Crystal 的类型推断,我遗漏了什么?解决方法是什么?

等效的基于 class 的方法是使 class 成为通用的:

require "json"

class Foo(T)
  def initialize(@bar : T)
  end

  def foo
    @bar.to_json
  end
end


puts Foo.new({"x" => 1, "y" => 2}).foo

实例变量需要以一种或另一种方式设置它们的类型,因为字典顺序类型流分析要困难得多,因此对它们进行分析也更慢。此外 classes 构建了程序的基础,因此尽可能缩小它们的类型不仅使编译器的工作更容易,也使它们更易于使用。对实例变量过于开放的类型限制会导致相当长且令人困惑的错误消息。

您可以在原始提案中阅读更多内容,该提案引入了要求对实例变量进行类型注释的更改:https://github.com/crystal-lang/crystal/issues/2390