Search code examples
crystal-lang

Seemingly trivial class example will not compile


I am attempting to configure properties of a specific type and guaranteed not to be nil with getters. This works fine for String or URI instance variables, however when attempting to do the same thing with an HTTP::Client the compiler gives an error that the instance variable is not initialized in all initialize methods.

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

The full error given by the compiler is:

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.

How can I appropriately initialize the @connection instance variable so that the crystal compiler is happy?


Solution

  • You have a typo there:

    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