rubymethodsattributesaccessorcrystal-lang

Does Crystal have attribute accessor methods like in Ruby?


Does the Crystal programming language have an equivalent to Ruby's attribute accessor methods? More specifically, does Crystal have equivalents to the following?

?


Solution

  • Yes, they're defined as macro.

    Basically:

    ruby crystal
    attr_accessor property
    attr_reader getter
    attr_writer setter

    Example

    class Person
      property name
    end
    

    is equal to

    class Person
      def name=(@name)
      end
    
      def name
        @name
      end
    end
    

    For more details see the Reference