How to pass a Class as argument of a method

Hi everyone!

Is there a way to pass a class as an argument of a function?

Example:

def safe(ex : T? = nil)
      yield
rescue ex
      puts ex
      puts typeof(ex)
end
def my_method(klass)
  pp klass
end

my_method Int32

Not sure what you’re specifically asking?

And how would you specify a default value?

def my_method(klass = String)
  pp klass
end

my_method Int32
my_method

It’s not really any differeant than any other value/default

2 Likes

:o Thank you!

Also for completeness sake, if you wanted to restrict the variable to a specific type of class; see https://crystal-lang.org/reference/syntax_and_semantics/type_restrictions.html#classes-as-restrictions.

1 Like