In Java, we are used to classes named *Utils: FileUtils, StringUtils an so on. The famous java.util.Collections belongs to the same breed. And the unpleasant part about these Utils-classes is that the code that uses them looks like this:
Those class names are always getting in the way. We can use static imports and get this:
This is a little better, but we have no or little help from the powerful code completion of the IDE. It would be so much better if we could say
But we don't want to implement all the possible methods inside the class List, right?
So, Kotlin (after C# and Gosu) introduces extension functions: a function declared outside the class List may be contributed to this type as an extension. This is denoted by prepending the receiver type (the one being extended) to the function name:
The this keyword inside an extension function corresponds to the receiver object (the one that is passed before the dot). Now, we can call such a function on any List<Int>:
Of course, this function makes sense for any List<T>, and we can make it generic:
We declare the generic type parameter before the function name for it to be available in the receiver type expression. See Generic functions.
To avoid confusion, we would like to emphasize that extension functions are resolved statically, i.e. they are not virtual by receiver type. On the other hand they can be member functions on some class and thus can be virtual in that class hierarchy.
AspectJ has inter-type declarations.
Groovy has metaclasses.
Scala makes heavy use of implicit conversions, i.e. wraps values into adapters at runtime.