You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@groovy.apache.org by "Eric Milles (Jira)" <ji...@apache.org> on 2023/07/31 18:57:00 UTC
[jira] [Created] (GROOVY-11143) Add extension method to source unit (same locality as static import)
Eric Milles created GROOVY-11143:
------------------------------------
Summary: Add extension method to source unit (same locality as static import)
Key: GROOVY-11143
URL: https://issues.apache.org/jira/browse/GROOVY-11143
Project: Groovy
Issue Type: New Feature
Reporter: Eric Milles
I have been poking around with the many ways to extend a class/object's functionality within groovy. To add a new method that can be called like any other instance method, there are a few possibilities:
1. modify the MetaClass
{code:groovy}
String.metaClass.ext = { ->
print delegate
}
"works".ext()
{code}
2. use a category class
{code:groovy}
@Category(String) class Cat {
void ext() {
println this
}
}
use (Cat) {
"works".ext()
}
{code}
3. apply a mixin
- create class similar to Cat in (2)
{code:groovy}
def str = "works"; str.metaClass.mixin(Cat)
str.ext()
{code}
4. apply a trait
{code:groovy}
trait Ext {
void ext() { println this.toLowerCase() } // see GROOVY-11142
}
"works".withTraits(Ext).ext()
{code}
5. create an extension moodule
- create class similar to Cat in (2)
- create META-INF/groovy/org.codehaus.groovy.runtime.ExtensionModule file
- build and deploy separately from current script / project
What I'm after is something that works as easily in a script or source file as static imports but lets me call like an extension method. And does not modify state outside of the current script (like metaclass or use). And works with static type checking.
Scala has an "extension" mechanism that is similar to static import but there is a keyword on the category class that lets compiler know the method is used like any other instance method. Scala used to provide "implicit" methods -- I've lost my familiarity with those.
I've seen "import static extension foo.Bar.baz;" for some language. (citation required)
And lastly, Kotlin provides a local extension like this:
{code:kotlin}
fun foo.Bar.baz() { x ->
// ...
}
{code}
--
This message was sent by Atlassian Jira
(v8.20.10#820010)