Crystal Lang:无法推断Rule的实例变量'@hash_value'的类型

时间:2018-10-31 11:43:42

标签: crystal-lang

这是我的水晶代码(摘要),但我认为它就在那里:

# spec_helper.rb
def fixtures
  rawhash = JSON.parse(File.read("spec/fixtures/state3.json"))
  rules = rawhash["rules"]
  id = rules.as_h.keys[0]
  hash =  rules[id]
  return id, hash
end

# rule_spec.rb
key, hash = fixtures
rule = Rule.new(key, hash)
rule.array(["name"])[0].must_equal "RpsIphone"

# rule.rb
class Rule  < HueResource

  getter :detail, :on, :name, :lights

  def initialize(key, hashvalue)
    super(key, hashvalue)
    @detail = "#{hashvalue["conditions"].length} conds => #{hashvalue["actions"].length} acts"
    @state.merge! ({"on" => hash_value["status"], "name" => @name, "detail" => @detail})
    gen_reskey("r")
  end
...
end

# hue resource.rb
class HueResource
  def initialize(key, hash_value)
    @hash_value = hash_value.as_h
    @lastupdated = @hash_value["state"]["lastupdated"]
    @detail = hash_value["type"]
    @name = hash_value["name"]
    @state = { "key" => key, "lastupdated" => @lastupdated, "detail" => @detail, "name" => @name}
  end

  def gen_reskey(detail)
    @state.merge!({ "id" => detail + @state["key"]})
  end
end

这是错误:

[Running] crystal "/Users/pitosalas/mydev/crystalplay/spec/rule_spec.cr"
Error in spec/rule_spec.cr:7: instantiating 'Rule.class#new(String, JSON::Any)'

    rule = Rule.new(key, hash)
                [32;1m^~~[0m

in src/rule.cr:7: instantiating 'super(String, JSON::Any)'

    super(key, hashvalue)
    [32;1m^~~~~[0m

in src/hue_resource.cr:3: [1mCan't infer the type of instance variable '@hash_value' of Rule

The type of a instance variable, if not declared explicitly with
`@hash_value : Type`, is inferred from assignments to it across
the whole program.

现在在我看来,在构造函数中,@hash_value被分配给hash_value.as_h,因此它将从那里知道类型。

还可以随时指出水晶的风格或惯用评论!

1 个答案:

答案 0 :(得分:4)

编译器无法从方法调用的返回类型(如hash_value.as_h)推断ivar类型。 reference of Type inference列出了编译器可以推断ivar类型的所有规则。

从方法调用中推断类型可能并非不可能,但更为复杂。在某种程度上,它可能涉及到语言,但是现在您必须使用显式类型注释,例如@hash_value : Hash(JSON::Any, JSON::Any)