Mat
Mat

Reputation: 2184

Crystal: abstract static method

Is it possible to define abstract static methods?

I'm trying:

abstract struct MyStruct
  abstract def self.myfun  # ERR
  abstract def MyStruct::myfun  # ERR
end

Upvotes: 2

Views: 476

Answers (2)

lipanski
lipanski

Reputation: 1763

I faced the same problem and figured out a (in my opinion) nicer solution:

abstract class Something
  module ClassMethods
    abstract def some_abstract_class_method
  end

  extend ClassMethods

  abstract def some_abstract_instance_method
end

The documentation mentions that module methods can be made abstract as well, so this builds on top of that.

Implementing this class without implementing the class method some_abstract_class_method will raise an error, as expected.

Upvotes: 3

bjmllr
bjmllr

Reputation: 99

Abstract class methods don't appear to be a language feature:

abstract class Abstract
  abstract self.doit
end
# => Syntax error in /home/bmiller/test.cr:23: unexpected token: self

However you could always delegate to an instance:

abstract class Parent
  def self.instance
    @@instance ||= new
  end

  def self.doit
    instance.doit
  end

  abstract def doit
end

class Child < Parent
  def doit
    "ok"
  end
end

p Parent.doit # => can't instantiate abstract class Parent
p Child.doit # => "ok"

Upvotes: 2

Related Questions