Hello! Can I extend existing class with a new method - for example, can I add new method to the Int32, String, Array or Hash classes/structs? Thanks!
Yes, however it’s not really extending as it happens with inheritance. https://play.crystal-lang.org/#/r/6kod
Classes/structs of the same name (when defined in multiple places) all get smooshed together, thus adding that custom method to the standard lib’s
String class. Also check out https://crystal-lang.org/reference/syntax_and_semantics/methods_and_instance_variables.html#redefining-methods-and-previousdef which talks about redefining methods.
A simple example of this is the
serialization stuff https://github.com/crystal-lang/crystal/blob/master/src/json/to_json.cr.
Where it is adding a
to_json method that details how to serialize that given type.
What exactly do you want to do, what’s your usecase?
Reopening classes and redefining methods is a delicate matter. There are often better solutions.
Solved by @Blacksmoke16 - I overlooked reopening classes. Sometimes is very useful to add methods to existing classes, imagine methods like “seconds” or serialization methods on the Int32 class (or another core classes). Solved, thanks!
Just to point out
#seconds already exists on
Int32. I gets inherited from
Also unless you are wanting a new serialization method
YAML are already supported in the stdlib.