我正在尝试配置特定类型的属性,并保证不要使用getters零。这对于String
或URI
实例变量正常工作,但是,当尝试使用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
实例变量,以使水晶编译器快乐?
您在那里有错字:
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
这对我有用。正如上面指出的那样,您有一个错别字,因此甚至可能不需要允许它。
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"))