MPS
 
Get MPS

Type Extension Methods

Last modified: 11 February 2024

The language jetbrains.mps.baseLanguage.extensionMethods provides a way to extend any valid MPS type with newly defined or overridden methods, akin to Java static methods.

Whereas static methods never become an internal part of the extended class and one has to always specify the "extended" object to operate on as one of the parameters to the extended method, with an extension method the new method gets added directly to the list of operations available on the target type.

So, provided we wanted to add a reverse method to the string type, instead of the good old "static method" way:

we would create new Extension Methods through New -> j.m.baseLanguage.extensionMethods/type extension, define the new method and tie it to the string class:

The very same mechanism can be used to override existing methods. And when in need to call the original method, just call it on this:

Since MPS does a good job to visually distinguish the original and overridden methods through the extension methods mechanism, you can't make a mistake picking the right one from the drop-down list.

extension-methods1.png

Obviously this mechanism can be used to implement orthogonal concepts on your own domain objects as well:

With the declaration as above, one could write an operation on type my_type: