看似琐碎的类示例不会编译

时间:2018-04-01 21:30:30

标签: crystal-lang

我正在尝试配置特定类型的属性,并保证不会使用getter为零。这适用于StringURI实例变量,但是当尝试使用HTTP::Client执行相同操作时,编译器会给出一个错误,即实例变量未在所有初始化方法中初始化。

require "http/client"

class Server
  getter uri : URI
  getter foo : String
  getter connnection : HTTP::Client

  def initialize(@uri)
    @foo = "Bar"
    @connection = HTTP::Client.new @uri
  end
end

编译器给出的完整错误是:

Error in src/server.cr:6: expanding macro

  getter connnection : HTTP::Client
  ^

in macro 'getter' expanded macro: macro_4613328608:113, line 4:

   1.       
   2.         
   3.           
>  4.             @connnection : HTTP::Client
   5. 
   6.             def connnection : HTTP::Client
   7.               @connnection
   8.             end
   9.           
  10.         
  11.       
  12.     

instance variable '@connnection' of Server was not initialized directly in all of the 'initialize' methods, rendering it nilable. Indirect initialization is not supported.

如何正确初始化@connection实例变量,以便水晶编译器满意?

2 个答案:

答案 0 :(得分:4)

你有一个错字:

require "http/client"

class Server
  getter uri : URI
  getter foo : String
  getter connnection : HTTP::Client
  #          ^

  def initialize(@uri)
    @foo = "Bar"
    @connection = HTTP::Client.new @uri
  end
end

答案 1 :(得分:2)

这对我有用。如上所述,你有一个拼写错误,所以甚至可能没有必要让它成为可能的。

require "http/client" 

class Server 
  getter uri : URI 
  getter foo : String 
  getter connection : HTTP::Client? 

  def initialize(@uri) 
    @foo = "Bar" 
    @connection = HTTP::Client.new @uri 
  end 
end 

Server.new(URI.parse("https://www.google.com")) 
相关问题