Search code examples
crystal-lang

How do I access an object's eigenclass in Crystal?


In Ruby, it's possible to access the eigenclass (or "singleton class") of an object by reopening it. This is particularly useful for defining "private class methods":

class Foo
  class << self
    private
    def declarative_method_name
    end
  end

  declarative_method_name
end

# Foo.declarative_method_name => ERROR!

However, in Crystal this is not syntax:

Syntax error in ./test.cr:2: expecting token 'CONST', not '<<'

  class << self
        ^

Is there another (or indeed any) way to achieve this in Crystal currently?


Solution

  • There's no eigenclass, or more commonly called singleton class in Ruby these days (given there's Object#singleton_class), in Crystal.

    However defining class methods and calling them on the class level is supported:

    class Foo
      private def self.declarative_method_name
        puts "hey"
      end
    
      declarative_method_name
    end
    

    https://carc.in/#/r/1316

    The def self. construct here is specialized by the compiler and there's no more general concept beneath it, yet.