tags: scala oops methods

We can add our own methods to an already existing classes which we don’t have access to the code of.

extension (c: SomeClass)
    def method1(arg: Type) = arg + c.value

How does it work?

  • This creates an extension method to a labelled method. This labelled method is internal to the compiler.
<extension> def method1(c: SomeClass) = arg + c.value

This can be invoked in two ways.

method1(instanceOfclass)
 
// or
instanceOfClass.method1

References

  1. https://docs.scala-lang.org/scala3/reference/contextual/extension-methods.html