Basic class code

Hi there, i’m back on Crystal and i’ve a basic question: what is the difference between these two class declarations?

  1. class Person
       @name : String
       @age : Int32
    
      def initialize(name, age)
      @name = name
      @age = age
     end
    
    def name
    @name
    end
    
     def age
      @age
     end
     end
    
  2.  class Person
        def initialize(name : String, age : Int32)
        @name = name
        @age = age
       end
    
    def name
    @name
    end
    
    def age
    @age
     end
    end
    

They’re functionally the same. Compiler knows the type of the two instance variables in the first example because they’re declared explicitly. In the second example it can infer it from the parameter type restrictions.

Tho I would say the more idiomatic approach would be like:

class Person
  getter name : String
  getter age : Int32

  def initialize(@name : String, @age : Int32); end
end
2 Likes

Ok, thx you :ok_hand: