Can I extend existing class with new method

#1

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!

1 Like

#2

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.

1 Like

#3

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.

0 Likes

#4

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!

0 Likes

#5

Just to point out #seconds already exists on Int32. I gets inherited from Int. https://crystal-lang.org/api/0.27.2/Int.html#seconds%3ATime%3A%3ASpan-instance-method

Also unless you are wanting a new serialization method JSON/YAML are already supported in the stdlib.

1 Like