[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6ACG2JDH1K9JRC8KD3X0WW1":3,"skill-same:01M6ACG2JDH1K9JRC8KD3X0WW1":68},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":23,"publishedAt":40,"linkOnly":41,"markdownContent":42,"markdownBody":43,"frontMatter":44,"refName":45,"commitSha":46,"skillDirectory":47,"forksCount":48,"repositoryHtmlUrl":49,"repositoryHomepageUrl":50,"ownerHtmlUrl":51,"ownerBlogUrl":52,"ownerDescription":6,"updatedAt":53,"install":54,"resources":67},"01M6ACG2JDH1K9JRC8KD3X0WW1","groovy-developer",null,"Expert guide for Groovy 5 development, covering concise syntax, closures, DSLs, metaprogramming, static compilation, and integration with Java 21 and Grails","apache\u002Fgrails-core","apache","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F47359?v=4","01M6AC83E6K4FDKK7HZ8WNMQKE","The Apache Software Foundation","01M6ACFVWFRRTGBQBMWZHV6TS9",2942,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fapache\u002Fgrails-core\u002Fblob\u002F8.0.x\u002F.agents\u002Fskills\u002Fgroovy-developer\u002FSKILL.md",[18],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39],"groovy","groovy developer","developer","grails","metaprogramming","development","java","expert","static","syntax","guide","for","with","concise","integration","java 21","2026-11-10 10:12:30",false,"---\nname: groovy-developer\ndescription: Expert guide for Groovy 5 development, covering concise syntax, closures, DSLs, metaprogramming, static compilation, and integration with Java 21 and Grails\nlicense: Apache-2.0\n---\n\u003C!--\nSPDX-License-Identifier: Apache-2.0\n\nLicensed to the Apache Software Foundation (ASF) under one or more contributor license agreements; and to You under the Apache License, Version 2.0. \n-->\n\n## What I Do\n\n- Provide deep expertise in Groovy 5.1, including core language features: syntax, closures, traits, GStrings, operators, and Groovy Truth.\n- Guide metaprogramming techniques: runtime (categories, ExpandoMetaClass, extension modules) and compile-time (AST transformations like @Immutable, @Builder, @Delegate, @Singleton, @Log, @Memoized).\n- Assist with DSL creation and usage (MarkupBuilder, JsonBuilder, builders for configuration).\n- Support testing with Spock Framework (BDD, data-driven tests, mocking) and built-in power assertions.\n- Help integrate Groovy with Java 21: joint compilation, Gradle builds, Grails, and Spring Boot.\n- Cover data handling: JSON\u002FXML parsing and building, Groovy SQL, collection processing.\n- Advise on performance: @CompileStatic, @TypeChecked, @GrailsCompileStatic for optimal execution.\n\n## When to Use Me\n\nActivate this skill for any Groovy-related task, including:\n\n- Writing or debugging Groovy classes in Grails domain, controllers, services, or taglibs.\n- Building or enhancing Gradle build scripts (build.gradle).\n- Creating DSLs for configuration, testing, or business rules.\n- Writing Spock specifications for unit and integration tests.\n- Migrating from older Groovy versions (2.x\u002F3.x\u002F4.x) to 5.1.\n- Performance optimization with static compilation.\n- Working with JSON\u002FXML data, GORM criteria queries, or builders.\n\n## Groovy 5 Key Features\n\n### Concise Syntax\n```groovy\n\u002F\u002F No semicolons required\ndef name = 'Grails'\n\n\u002F\u002F Optional parentheses for method calls\nprintln 'Hello World'\nlist.each { println it }\n\n\u002F\u002F Optional return keyword\nString greet(String name) {\n    \"Hello, $name\"  \u002F\u002F Last expression is returned (GString needs double quotes)\n}\n```\n\n### GStrings (String Interpolation)\n```groovy\ndef user = \"Alice\"\ndef count = 42\n\n\u002F\u002F Simple interpolation\nprintln \"User: $user\"\n\n\u002F\u002F Expression interpolation\nprintln \"Items: ${count * 2}\"\n\n\u002F\u002F Lazy GStrings (evaluated when accessed)\ndef lazy = \"Count is ${ -> counter }\"\n\n\u002F\u002F Multi-line strings\ndef sql = \"\"\"\n    SELECT * FROM users\n    WHERE name = '$user'\n    ORDER BY created_at\n\"\"\"\n```\n\n### Closures\n```groovy\n\u002F\u002F Basic closure\ndef greet = { name -> \"Hello, $name\" }\nprintln greet(\"World\")\n\n\u002F\u002F Implicit 'it' parameter\ndef twice = { it * 2 }\nprintln [1, 2, 3].collect(twice)\n\n\u002F\u002F Closure with delegate (for DSLs)\ndef configure = {\n    name = \"MyApp\"\n    version = \"1.0\"\n}\nconfigure.delegate = new Config()\nconfigure.resolveStrategy = Closure.DELEGATE_FIRST\nconfigure()\n\n\u002F\u002F Method references\ndef upper = String.&toUpperCase\nprintln [\"a\", \"b\"].collect(upper)\n```\n\n### Safe Navigation and Elvis Operator\n```groovy\n\u002F\u002F Safe navigation - returns null if any part is null\ndef city = user?.address?.city\n\n\u002F\u002F Elvis operator - default value if null\ndef name = user?.name ?: \"Anonymous\"\n\n\u002F\u002F Safe method calls\ndef length = text?.length() ?: 0\n\n\u002F\u002F Combine with collections\ndef firstTitle = books?.first()?.title ?: \"No books\"\n```\n\n### Ternary Operator\n```groovy\n\u002F\u002F Use ternary operators only for simple conditions.\n\u002F\u002F Split long ternary expressions into multiple lines.\n\u002F\u002F Align `?` and `:` branches for readability.\nString message = condition\n        ? \"Value when true\"\n        : \"Value when false\"\n```\n\n### Spread Operator\n```groovy\n\u002F\u002F Spread operator for collections\ndef names = users*.name  \u002F\u002F Same as users.collect { it.name }\n\n\u002F\u002F Spread for method arguments\ndef args = [1, 2, 3]\nsomeMethod(*args)\n\n\u002F\u002F Spread in list literals\ndef combined = [*list1, *list2]\n```\n\n### Collection Literals and Methods\n```groovy\n\u002F\u002F List literal\ndef list = [1, 2, 3, 4, 5]\n\n\u002F\u002F Map literal\ndef map = [name: \"Grails\", version: 7]\n\n\u002F\u002F Range\ndef range = 1..10\ndef exclusive = 1..\u003C10\n\n\u002F\u002F Powerful collection methods\nlist.find { it > 3 }           \u002F\u002F First match: 4\nlist.findAll { it > 3 }        \u002F\u002F All matches: [4, 5]\nlist.any { it > 3 }            \u002F\u002F true\nlist.every { it > 0 }          \u002F\u002F true\nlist.groupBy { it % 2 }        \u002F\u002F [0:[2,4], 1:[1,3,5]]\nlist.collectEntries { [it, it * 2] }  \u002F\u002F [1:2, 2:4, ...]\n\n\u002F\u002F Sorting\nlist.sort { a, b -> b \u003C=> a }  \u002F\u002F Descending\nlist.sort { -it }              \u002F\u002F Descending (numeric)\n```\n\n### Groovy Truth\n```groovy\n\u002F\u002F Falsy values: null, empty string, empty collection, 0, false\nif (list) { }      \u002F\u002F True if not null and not empty\nif (string) { }    \u002F\u002F True if not null and not blank\nif (number) { }    \u002F\u002F True if not 0\n\n\u002F\u002F Useful in conditionals\ndef items = getItems() ?: []  \u002F\u002F Default to empty list\n```\n\n### Records\n```groovy\n\u002F\u002F Immutable data class\nrecord Point(int x, int y) {}\n\ndef p = new Point(10, 20)\nprintln p.x()  \u002F\u002F 10\nprintln p      \u002F\u002F Point[x=10, y=20]\n```\n\n### Traits\n```groovy\ntrait Auditable {\n    Date dateCreated\n    Date lastUpdated\n\n    def beforeInsert() {\n        dateCreated = new Date()\n    }\n\n    def beforeUpdate() {\n        lastUpdated = new Date()\n    }\n}\n\nclass Book implements Auditable {\n    String title\n}\n```\n\n## Static Compilation\n\n### @CompileStatic\nEnables static type checking and compilation for better performance:\n```groovy\nimport groovy.transform.CompileStatic\n\n@CompileStatic\nclass BookService {\n    List\u003CBook> findByAuthor(String author) {\n        Book.findAllByAuthor(author)\n    }\n\n    int calculateTotal(List\u003CInteger> prices) {\n        prices.sum() as int\n    }\n}\n```\n\n### @TypeChecked\nType checking without full static compilation:\n```groovy\nimport groovy.transform.TypeChecked\n\n@TypeChecked\nvoid process(String input) {\n    println input.toUppercase()  \u002F\u002F Compile error: method not found\n}\n```\n\n### @GrailsCompileStatic\nGrails-aware static compilation that understands dynamic finders:\n```groovy\nimport grails.compiler.GrailsCompileStatic\n\n@GrailsCompileStatic\nclass BookController {\n    def show(Long id) {\n        respond Book.findByIdAndActive(id, true)  \u002F\u002F Dynamic finder works with @GrailsCompileStatic\n    }\n}\n```\n\n## AST Transformations\n\n### @Immutable\n```groovy\nimport groovy.transform.Immutable\n\n@Immutable\nclass Person {\n    String name\n    int age\n}\n\ndef p = new Person(name: \"Alice\", age: 30)\n\u002F\u002F p.name = \"Bob\"  \u002F\u002F Error: read-only\n```\n\n### @Builder\n```groovy\nimport groovy.transform.builder.Builder\n\n@Builder\nclass Email {\n    String to\n    String subject\n    String body\n}\n\ndef email = Email.builder()\n    .to(\"user@example.com\")\n    .subject(\"Hello\")\n    .body(\"Content here\")\n    .build()\n```\n\n### @Delegate\n```groovy\nimport groovy.lang.Delegate\n\nclass EnhancedList\u003CT> {\n    @Delegate List\u003CT> list = []\n\n    T secondLast() {\n        list[-2]\n    }\n}\n\ndef enhanced = new EnhancedList\u003CString>()\nenhanced.add(\"a\")  \u002F\u002F Delegated to list\nenhanced.add(\"b\")\nprintln enhanced.secondLast()  \u002F\u002F \"a\"\n```\n\n### @Singleton\n```groovy\nimport groovy.lang.Singleton\n\n@Singleton\nclass ConfigManager {\n    Map settings = [:]\n}\n\nConfigManager.instance.settings['key'] = 'value'\n```\n\n### @Memoized\n```groovy\nimport groovy.transform.Memoized\n\nclass Calculator {\n    @Memoized\n    BigInteger fibonacci(int n) {\n        if (n \u003C= 1) return n\n        fibonacci(n - 1) + fibonacci(n - 2)\n    }\n}\n```\n\n### @Log Variants\n```groovy\nimport groovy.util.logging.Slf4j\n\n@Slf4j\nclass BookService {\n    def save(Book book) {\n        log.info \"Saving book: ${book.title}\"\n        \u002F\u002F ...\n    }\n}\n```\n\n## Builders and DSLs\n\n### JsonBuilder\n```groovy\nimport groovy.json.JsonBuilder\n\ndef builder = new JsonBuilder()\nbuilder {\n    name \"Grails\"\n    version 7\n    features([\"GORM\", \"GSP\", \"Plugins\"])\n    metadata {\n        author \"Grails Team\"\n        license \"Apache 2.0\"\n    }\n}\nprintln builder.toPrettyString()\n```\n\n### JsonSlurper\n```groovy\nimport groovy.json.JsonSlurper\n\ndef json = '{\"name\": \"Grails\", \"version\": 7}'\ndef data = new JsonSlurper().parseText(json)\nprintln data.name  \u002F\u002F Grails\n```\n\n### MarkupBuilder (XML\u002FHTML)\n```groovy\nimport groovy.xml.MarkupBuilder\n\ndef writer = new StringWriter()\ndef xml = new MarkupBuilder(writer)\nxml.books {\n    book(id: 1) {\n        title \"Grails Guide\"\n        author \"Team\"\n    }\n}\nprintln writer.toString()\n```\n\n### Custom DSL Example\n```groovy\nclass HtmlBuilder {\n    def html(@DelegatesTo(HtmlBuilder) Closure c) {\n        c.delegate = this\n        c.resolveStrategy = Closure.DELEGATE_FIRST\n        \"\u003Chtml>${c()}\u003C\u002Fhtml>\"\n    }\n\n    def body(String content) {\n        \"\u003Cbody>$content\u003C\u002Fbody>\"\n    }\n}\n\ndef builder = new HtmlBuilder()\ndef result = builder.html {\n    body \"Hello World\"\n}\n```\n\n## Testing with Spock\n\n### Basic Specification\n```groovy\nclass BookServiceSpec extends Specification {\n\n    def service = new BookService()\n\n    def \"should find book by title\"() {\n        given: \"a book title\"\n        def title = \"Grails Guide\"\n\n        when: \"searching for the book\"\n        def book = service.findByTitle(title)\n\n        then: \"the book is found\"\n        book != null\n        book.title == title\n    }\n}\n```\n\n### Data-Driven Tests\n```groovy\n@Unroll\ndef \"max of #a and #b is #expected\"() {\n    expect:\n    Math.max(a, b) == expected\n\n    where:\n    a | b || expected\n    1 | 3 || 3\n    7 | 4 || 7\n    0 | 0 || 0\n}\n```\n\n### Mocking\n```groovy\ndef \"should call repository when saving\"() {\n    given:\n    def repo = Mock(BookRepository)\n    def service = new BookService(repo)\n    def book = new Book(title: \"Test\")\n\n    when:\n    service.save(book)\n\n    then:\n    1 * repo.save(book)\n}\n```\n\n### Exception Testing\n```groovy\ndef \"should throw exception for invalid input\"() {\n    when:\n    service.process(null)\n\n    then:\n    thrown(IllegalArgumentException)\n}\n```\n\n## Groovy SQL\n```groovy\nimport groovy.sql.Sql\n\ndef sql = Sql.newInstance(dataSource)\n\n\u002F\u002F Query\nsql.eachRow(\"SELECT * FROM books WHERE author = ?\", [authorName]) { row ->\n    println \"${row.title} by ${row.author}\"\n}\n\n\u002F\u002F Insert\nsql.execute(\"INSERT INTO books (title, author) VALUES (?, ?)\",\n            [title, author])\n\n\u002F\u002F With GString (auto-parameterized)\nsql.execute(\"INSERT INTO books (title) VALUES ($title)\")\n```\n\n## Best Practices\n\n### Performance\n- Use `@CompileStatic` or `@GrailsCompileStatic` in production code.\n- Avoid runtime metaprogramming in hot paths.\n- Prefer `collect`\u002F`findAll` over manual loops.\n- Use `@Memoized` for expensive computations.\n\n### Code Style\n- Use safe navigation (`?.`) instead of null checks.\n- Prefer Elvis operator (`?:`) for default values.\n- Use GStrings for string interpolation.\n- Prefer traits over inheritance for mixins.\n- Use explicit types for public APIs, `def` for local variables.\n- Always use parentheses in method calls for clarity.\n\n### Grails-Specific\n- Use `@GrailsCompileStatic` instead of `@CompileStatic` in Grails artefact classes if needed.\n- Leverage GORM dynamic finders and where queries.\n- Use command objects for form binding and validation.\n- Follow convention over configuration.\n\n## Common Pitfalls\n\n- **`==` vs `is`**: `==` calls `equals()`, use `is` for identity comparison (same as Java).\n- **GString in maps**: GStrings don't work as map keys; use `\"key$idx\".toString()` if needed.\n- **Closure scope**: Understand `delegate`, `owner`, and `this` in closures.\n- **Optional parentheses**: Can cause ambiguity; always use parentheses for clarity.\n- **Static imports**: Always use explicit imports for statically imported methods.\n\n## Semantic Pathway and Defensive Lifecycle Protocol\n\nWhen writing or testing Groovy classes coordinating resources, lifecycle hooks, transaction boundaries, or multi-branch strategies, apply this mandatory engineering protocol:\n\n### 1. Collaborator Nullability Analysis\n- Determine whether external or looked-up collaborators (`DataSource`, `HttpServletRequest`, `SessionFactory`, `ClassLoader`, `TransactionStatus`, etc.) can ever be `null` in non-standard environments (e.g. standalone unit tests, mock frameworks, alternative SPI providers, or uninitialized scopes).\n- Before passing any collaborator to external libraries or SPIs that enforce strict non-null assertions (such as Spring's `TransactionSynchronizationManager`, `Assert.notNull()`, or Jakarta Servlet APIs), guard with explicit null checks (e.g. `dataSource != null ? txResources.getResource(dataSource) : null`).\n- Safe navigation (`?.`) does not protect arguments passed into strict Java methods expecting non-null parameters (`method(obj?.property)` passes `null` if `obj` is null).\n\n### 2. Early Failure Injection and Cleanup Symmetry\n- Trace what happens if an exception is thrown *before* a resource is registered, bound, or opened (e.g., `openSession()`, `getConnection()`, or `prepare()` failing).\n- In `finally` or cleanup blocks, use safe unbinding (`unbindResourceIfPossible` instead of unconditional `unbindResource`) so a missing binding does not throw a secondary `IllegalStateException` or `NullPointerException` that masks the primary root cause.\n- Guard against calling methods on half-initialized objects in `finally` blocks (e.g., check `newSession != null` before `closeSession(newSession)`).\n- Symmetrically undo any intermediate state changes (e.g., restore previously suspended holders\u002Fsynchronizations) even when initial acquisition fails.\n\n### 3. Exhaustive Decision Matrix Branching\n- When selecting a strategy or executing conditional flows (e.g. `from(...)` factory methods, state transitions):\n  - Explicitly define the combinatorial state table (e.g. `holder exists \u002F null` × `transaction active \u002F inactive` × `synchronization active \u002F inactive` × `lazy \u002F non-lazy`).\n  - Verify every branch resolves to an intentional, well-defined strategy.\n  - Use Spock data-driven tables (`where:`) to verify every branch of the decision matrix, including compound negatives.\n\n### 4. Authentic Boundary and Failure Testing\n- Tests covering exception translation or failure recovery must exercise real database\u002Fruntime failure modes (e.g., genuine column length overruns, constraint violations, closed connection probes) rather than artificial subclass overrides or mocks throwing synthetic exceptions that bypass real translator chains.\n\n## Resources\n\n- **Groovy 5 Documentation**: https:\u002F\u002Fgroovy-lang.org\u002Fdocumentation.html#all-versions (select latest 5.1.x)\n- **Groovy Style Guide**: https:\u002F\u002Fgroovy-lang.org\u002Fstyle-guide.html\n- **GORM Documentation**: https:\u002F\u002Fgrails.apache.org\u002Fdocs\u002Flatest\u002Fgrails-data\u002F\n- **Spock Framework**: https:\u002F\u002Fspockframework.org\u002Fspock\u002Fdocs\u002F2.4\u002Fall_in_one.html\n","\u003C!--\nSPDX-License-Identifier: Apache-2.0\n\nLicensed to the Apache Software Foundation (ASF) under one or more contributor license agreements; and to You under the Apache License, Version 2.0. \n-->\n\n## What I Do\n\n- Provide deep expertise in Groovy 5.1, including core language features: syntax, closures, traits, GStrings, operators, and Groovy Truth.\n- Guide metaprogramming techniques: runtime (categories, ExpandoMetaClass, extension modules) and compile-time (AST transformations like @Immutable, @Builder, @Delegate, @Singleton, @Log, @Memoized).\n- Assist with DSL creation and usage (MarkupBuilder, JsonBuilder, builders for configuration).\n- Support testing with Spock Framework (BDD, data-driven tests, mocking) and built-in power assertions.\n- Help integrate Groovy with Java 21: joint compilation, Gradle builds, Grails, and Spring Boot.\n- Cover data handling: JSON\u002FXML parsing and building, Groovy SQL, collection processing.\n- Advise on performance: @CompileStatic, @TypeChecked, @GrailsCompileStatic for optimal execution.\n\n## When to Use Me\n\nActivate this skill for any Groovy-related task, including:\n\n- Writing or debugging Groovy classes in Grails domain, controllers, services, or taglibs.\n- Building or enhancing Gradle build scripts (build.gradle).\n- Creating DSLs for configuration, testing, or business rules.\n- Writing Spock specifications for unit and integration tests.\n- Migrating from older Groovy versions (2.x\u002F3.x\u002F4.x) to 5.1.\n- Performance optimization with static compilation.\n- Working with JSON\u002FXML data, GORM criteria queries, or builders.\n\n## Groovy 5 Key Features\n\n### Concise Syntax\n```groovy\n\u002F\u002F No semicolons required\ndef name = 'Grails'\n\n\u002F\u002F Optional parentheses for method calls\nprintln 'Hello World'\nlist.each { println it }\n\n\u002F\u002F Optional return keyword\nString greet(String name) {\n    \"Hello, $name\"  \u002F\u002F Last expression is returned (GString needs double quotes)\n}\n```\n\n### GStrings (String Interpolation)\n```groovy\ndef user = \"Alice\"\ndef count = 42\n\n\u002F\u002F Simple interpolation\nprintln \"User: $user\"\n\n\u002F\u002F Expression interpolation\nprintln \"Items: ${count * 2}\"\n\n\u002F\u002F Lazy GStrings (evaluated when accessed)\ndef lazy = \"Count is ${ -> counter }\"\n\n\u002F\u002F Multi-line strings\ndef sql = \"\"\"\n    SELECT * FROM users\n    WHERE name = '$user'\n    ORDER BY created_at\n\"\"\"\n```\n\n### Closures\n```groovy\n\u002F\u002F Basic closure\ndef greet = { name -> \"Hello, $name\" }\nprintln greet(\"World\")\n\n\u002F\u002F Implicit 'it' parameter\ndef twice = { it * 2 }\nprintln [1, 2, 3].collect(twice)\n\n\u002F\u002F Closure with delegate (for DSLs)\ndef configure = {\n    name = \"MyApp\"\n    version = \"1.0\"\n}\nconfigure.delegate = new Config()\nconfigure.resolveStrategy = Closure.DELEGATE_FIRST\nconfigure()\n\n\u002F\u002F Method references\ndef upper = String.&toUpperCase\nprintln [\"a\", \"b\"].collect(upper)\n```\n\n### Safe Navigation and Elvis Operator\n```groovy\n\u002F\u002F Safe navigation - returns null if any part is null\ndef city = user?.address?.city\n\n\u002F\u002F Elvis operator - default value if null\ndef name = user?.name ?: \"Anonymous\"\n\n\u002F\u002F Safe method calls\ndef length = text?.length() ?: 0\n\n\u002F\u002F Combine with collections\ndef firstTitle = books?.first()?.title ?: \"No books\"\n```\n\n### Ternary Operator\n```groovy\n\u002F\u002F Use ternary operators only for simple conditions.\n\u002F\u002F Split long ternary expressions into multiple lines.\n\u002F\u002F Align `?` and `:` branches for readability.\nString message = condition\n        ? \"Value when true\"\n        : \"Value when false\"\n```\n\n### Spread Operator\n```groovy\n\u002F\u002F Spread operator for collections\ndef names = users*.name  \u002F\u002F Same as users.collect { it.name }\n\n\u002F\u002F Spread for method arguments\ndef args = [1, 2, 3]\nsomeMethod(*args)\n\n\u002F\u002F Spread in list literals\ndef combined = [*list1, *list2]\n```\n\n### Collection Literals and Methods\n```groovy\n\u002F\u002F List literal\ndef list = [1, 2, 3, 4, 5]\n\n\u002F\u002F Map literal\ndef map = [name: \"Grails\", version: 7]\n\n\u002F\u002F Range\ndef range = 1..10\ndef exclusive = 1..\u003C10\n\n\u002F\u002F Powerful collection methods\nlist.find { it > 3 }           \u002F\u002F First match: 4\nlist.findAll { it > 3 }        \u002F\u002F All matches: [4, 5]\nlist.any { it > 3 }            \u002F\u002F true\nlist.every { it > 0 }          \u002F\u002F true\nlist.groupBy { it % 2 }        \u002F\u002F [0:[2,4], 1:[1,3,5]]\nlist.collectEntries { [it, it * 2] }  \u002F\u002F [1:2, 2:4, ...]\n\n\u002F\u002F Sorting\nlist.sort { a, b -> b \u003C=> a }  \u002F\u002F Descending\nlist.sort { -it }              \u002F\u002F Descending (numeric)\n```\n\n### Groovy Truth\n```groovy\n\u002F\u002F Falsy values: null, empty string, empty collection, 0, false\nif (list) { }      \u002F\u002F True if not null and not empty\nif (string) { }    \u002F\u002F True if not null and not blank\nif (number) { }    \u002F\u002F True if not 0\n\n\u002F\u002F Useful in conditionals\ndef items = getItems() ?: []  \u002F\u002F Default to empty list\n```\n\n### Records\n```groovy\n\u002F\u002F Immutable data class\nrecord Point(int x, int y) {}\n\ndef p = new Point(10, 20)\nprintln p.x()  \u002F\u002F 10\nprintln p      \u002F\u002F Point[x=10, y=20]\n```\n\n### Traits\n```groovy\ntrait Auditable {\n    Date dateCreated\n    Date lastUpdated\n\n    def beforeInsert() {\n        dateCreated = new Date()\n    }\n\n    def beforeUpdate() {\n        lastUpdated = new Date()\n    }\n}\n\nclass Book implements Auditable {\n    String title\n}\n```\n\n## Static Compilation\n\n### @CompileStatic\nEnables static type checking and compilation for better performance:\n```groovy\nimport groovy.transform.CompileStatic\n\n@CompileStatic\nclass BookService {\n    List\u003CBook> findByAuthor(String author) {\n        Book.findAllByAuthor(author)\n    }\n\n    int calculateTotal(List\u003CInteger> prices) {\n        prices.sum() as int\n    }\n}\n```\n\n### @TypeChecked\nType checking without full static compilation:\n```groovy\nimport groovy.transform.TypeChecked\n\n@TypeChecked\nvoid process(String input) {\n    println input.toUppercase()  \u002F\u002F Compile error: method not found\n}\n```\n\n### @GrailsCompileStatic\nGrails-aware static compilation that understands dynamic finders:\n```groovy\nimport grails.compiler.GrailsCompileStatic\n\n@GrailsCompileStatic\nclass BookController {\n    def show(Long id) {\n        respond Book.findByIdAndActive(id, true)  \u002F\u002F Dynamic finder works with @GrailsCompileStatic\n    }\n}\n```\n\n## AST Transformations\n\n### @Immutable\n```groovy\nimport groovy.transform.Immutable\n\n@Immutable\nclass Person {\n    String name\n    int age\n}\n\ndef p = new Person(name: \"Alice\", age: 30)\n\u002F\u002F p.name = \"Bob\"  \u002F\u002F Error: read-only\n```\n\n### @Builder\n```groovy\nimport groovy.transform.builder.Builder\n\n@Builder\nclass Email {\n    String to\n    String subject\n    String body\n}\n\ndef email = Email.builder()\n    .to(\"user@example.com\")\n    .subject(\"Hello\")\n    .body(\"Content here\")\n    .build()\n```\n\n### @Delegate\n```groovy\nimport groovy.lang.Delegate\n\nclass EnhancedList\u003CT> {\n    @Delegate List\u003CT> list = []\n\n    T secondLast() {\n        list[-2]\n    }\n}\n\ndef enhanced = new EnhancedList\u003CString>()\nenhanced.add(\"a\")  \u002F\u002F Delegated to list\nenhanced.add(\"b\")\nprintln enhanced.secondLast()  \u002F\u002F \"a\"\n```\n\n### @Singleton\n```groovy\nimport groovy.lang.Singleton\n\n@Singleton\nclass ConfigManager {\n    Map settings = [:]\n}\n\nConfigManager.instance.settings['key'] = 'value'\n```\n\n### @Memoized\n```groovy\nimport groovy.transform.Memoized\n\nclass Calculator {\n    @Memoized\n    BigInteger fibonacci(int n) {\n        if (n \u003C= 1) return n\n        fibonacci(n - 1) + fibonacci(n - 2)\n    }\n}\n```\n\n### @Log Variants\n```groovy\nimport groovy.util.logging.Slf4j\n\n@Slf4j\nclass BookService {\n    def save(Book book) {\n        log.info \"Saving book: ${book.title}\"\n        \u002F\u002F ...\n    }\n}\n```\n\n## Builders and DSLs\n\n### JsonBuilder\n```groovy\nimport groovy.json.JsonBuilder\n\ndef builder = new JsonBuilder()\nbuilder {\n    name \"Grails\"\n    version 7\n    features([\"GORM\", \"GSP\", \"Plugins\"])\n    metadata {\n        author \"Grails Team\"\n        license \"Apache 2.0\"\n    }\n}\nprintln builder.toPrettyString()\n```\n\n### JsonSlurper\n```groovy\nimport groovy.json.JsonSlurper\n\ndef json = '{\"name\": \"Grails\", \"version\": 7}'\ndef data = new JsonSlurper().parseText(json)\nprintln data.name  \u002F\u002F Grails\n```\n\n### MarkupBuilder (XML\u002FHTML)\n```groovy\nimport groovy.xml.MarkupBuilder\n\ndef writer = new StringWriter()\ndef xml = new MarkupBuilder(writer)\nxml.books {\n    book(id: 1) {\n        title \"Grails Guide\"\n        author \"Team\"\n    }\n}\nprintln writer.toString()\n```\n\n### Custom DSL Example\n```groovy\nclass HtmlBuilder {\n    def html(@DelegatesTo(HtmlBuilder) Closure c) {\n        c.delegate = this\n        c.resolveStrategy = Closure.DELEGATE_FIRST\n        \"\u003Chtml>${c()}\u003C\u002Fhtml>\"\n    }\n\n    def body(String content) {\n        \"\u003Cbody>$content\u003C\u002Fbody>\"\n    }\n}\n\ndef builder = new HtmlBuilder()\ndef result = builder.html {\n    body \"Hello World\"\n}\n```\n\n## Testing with Spock\n\n### Basic Specification\n```groovy\nclass BookServiceSpec extends Specification {\n\n    def service = new BookService()\n\n    def \"should find book by title\"() {\n        given: \"a book title\"\n        def title = \"Grails Guide\"\n\n        when: \"searching for the book\"\n        def book = service.findByTitle(title)\n\n        then: \"the book is found\"\n        book != null\n        book.title == title\n    }\n}\n```\n\n### Data-Driven Tests\n```groovy\n@Unroll\ndef \"max of #a and #b is #expected\"() {\n    expect:\n    Math.max(a, b) == expected\n\n    where:\n    a | b || expected\n    1 | 3 || 3\n    7 | 4 || 7\n    0 | 0 || 0\n}\n```\n\n### Mocking\n```groovy\ndef \"should call repository when saving\"() {\n    given:\n    def repo = Mock(BookRepository)\n    def service = new BookService(repo)\n    def book = new Book(title: \"Test\")\n\n    when:\n    service.save(book)\n\n    then:\n    1 * repo.save(book)\n}\n```\n\n### Exception Testing\n```groovy\ndef \"should throw exception for invalid input\"() {\n    when:\n    service.process(null)\n\n    then:\n    thrown(IllegalArgumentException)\n}\n```\n\n## Groovy SQL\n```groovy\nimport groovy.sql.Sql\n\ndef sql = Sql.newInstance(dataSource)\n\n\u002F\u002F Query\nsql.eachRow(\"SELECT * FROM books WHERE author = ?\", [authorName]) { row ->\n    println \"${row.title} by ${row.author}\"\n}\n\n\u002F\u002F Insert\nsql.execute(\"INSERT INTO books (title, author) VALUES (?, ?)\",\n            [title, author])\n\n\u002F\u002F With GString (auto-parameterized)\nsql.execute(\"INSERT INTO books (title) VALUES ($title)\")\n```\n\n## Best Practices\n\n### Performance\n- Use `@CompileStatic` or `@GrailsCompileStatic` in production code.\n- Avoid runtime metaprogramming in hot paths.\n- Prefer `collect`\u002F`findAll` over manual loops.\n- Use `@Memoized` for expensive computations.\n\n### Code Style\n- Use safe navigation (`?.`) instead of null checks.\n- Prefer Elvis operator (`?:`) for default values.\n- Use GStrings for string interpolation.\n- Prefer traits over inheritance for mixins.\n- Use explicit types for public APIs, `def` for local variables.\n- Always use parentheses in method calls for clarity.\n\n### Grails-Specific\n- Use `@GrailsCompileStatic` instead of `@CompileStatic` in Grails artefact classes if needed.\n- Leverage GORM dynamic finders and where queries.\n- Use command objects for form binding and validation.\n- Follow convention over configuration.\n\n## Common Pitfalls\n\n- **`==` vs `is`**: `==` calls `equals()`, use `is` for identity comparison (same as Java).\n- **GString in maps**: GStrings don't work as map keys; use `\"key$idx\".toString()` if needed.\n- **Closure scope**: Understand `delegate`, `owner`, and `this` in closures.\n- **Optional parentheses**: Can cause ambiguity; always use parentheses for clarity.\n- **Static imports**: Always use explicit imports for statically imported methods.\n\n## Semantic Pathway and Defensive Lifecycle Protocol\n\nWhen writing or testing Groovy classes coordinating resources, lifecycle hooks, transaction boundaries, or multi-branch strategies, apply this mandatory engineering protocol:\n\n### 1. Collaborator Nullability Analysis\n- Determine whether external or looked-up collaborators (`DataSource`, `HttpServletRequest`, `SessionFactory`, `ClassLoader`, `TransactionStatus`, etc.) can ever be `null` in non-standard environments (e.g. standalone unit tests, mock frameworks, alternative SPI providers, or uninitialized scopes).\n- Before passing any collaborator to external libraries or SPIs that enforce strict non-null assertions (such as Spring's `TransactionSynchronizationManager`, `Assert.notNull()`, or Jakarta Servlet APIs), guard with explicit null checks (e.g. `dataSource != null ? txResources.getResource(dataSource) : null`).\n- Safe navigation (`?.`) does not protect arguments passed into strict Java methods expecting non-null parameters (`method(obj?.property)` passes `null` if `obj` is null).\n\n### 2. Early Failure Injection and Cleanup Symmetry\n- Trace what happens if an exception is thrown *before* a resource is registered, bound, or opened (e.g., `openSession()`, `getConnection()`, or `prepare()` failing).\n- In `finally` or cleanup blocks, use safe unbinding (`unbindResourceIfPossible` instead of unconditional `unbindResource`) so a missing binding does not throw a secondary `IllegalStateException` or `NullPointerException` that masks the primary root cause.\n- Guard against calling methods on half-initialized objects in `finally` blocks (e.g., check `newSession != null` before `closeSession(newSession)`).\n- Symmetrically undo any intermediate state changes (e.g., restore previously suspended holders\u002Fsynchronizations) even when initial acquisition fails.\n\n### 3. Exhaustive Decision Matrix Branching\n- When selecting a strategy or executing conditional flows (e.g. `from(...)` factory methods, state transitions):\n  - Explicitly define the combinatorial state table (e.g. `holder exists \u002F null` × `transaction active \u002F inactive` × `synchronization active \u002F inactive` × `lazy \u002F non-lazy`).\n  - Verify every branch resolves to an intentional, well-defined strategy.\n  - Use Spock data-driven tables (`where:`) to verify every branch of the decision matrix, including compound negatives.\n\n### 4. Authentic Boundary and Failure Testing\n- Tests covering exception translation or failure recovery must exercise real database\u002Fruntime failure modes (e.g., genuine column length overruns, constraint violations, closed connection probes) rather than artificial subclass overrides or mocks throwing synthetic exceptions that bypass real translator chains.\n\n## Resources\n\n- **Groovy 5 Documentation**: https:\u002F\u002Fgroovy-lang.org\u002Fdocumentation.html#all-versions (select latest 5.1.x)\n- **Groovy Style Guide**: https:\u002F\u002Fgroovy-lang.org\u002Fstyle-guide.html\n- **GORM Documentation**: https:\u002F\u002Fgrails.apache.org\u002Fdocs\u002Flatest\u002Fgrails-data\u002F\n- **Spock Framework**: https:\u002F\u002Fspockframework.org\u002Fspock\u002Fdocs\u002F2.4\u002Fall_in_one.html\n",{"name":5,"license":15,"description":7},"8.0.x","88272db2f39e7254a950d4aacad03aedc545337c",".agents\u002Fskills\u002Fgroovy-developer",979,"https:\u002F\u002Fgithub.com\u002Fapache\u002Fgrails-core","https:\u002F\u002Fgrails.apache.org\u002F","https:\u002F\u002Fgithub.com\u002Fapache","https:\u002F\u002Fwww.apache.org\u002F","2026-11-15 03:12:29",{"source":8,"skillName":5,"commands":55,"prompt":65,"zipAvailable":66},[56,59,62],{"tool":57,"command":58},"npx","npx skills add apache\u002Fgrails-core --skill groovy-developer",{"tool":60,"command":61},"bunx","bunx skills add apache\u002Fgrails-core --skill groovy-developer",{"tool":63,"command":64},"pnpm","pnpm dlx skills add apache\u002Fgrails-core --skill groovy-developer","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fapache\u002Fgrails-core\u002Fblob\u002F8.0.x\u002F.agents\u002Fskills\u002Fgroovy-developer\u002FSKILL.md",true,[],[69,76,82,88,94,100],{"skillNo":70,"name":71,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":75},"01M7B5APRW1EKGNHWGDMK15JE5","violation-fixer","https:\u002F\u002Fgithub.com\u002Fapache\u002Fgrails-core\u002Fblob\u002F8.0.x\u002F.claude\u002Fskills\u002Fviolation-fixer\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":77,"name":78,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":75},"01M7B5AMFA8A8560CGDCFHW3SK","test-fixer","https:\u002F\u002Fgithub.com\u002Fapache\u002Fgrails-core\u002Fblob\u002F8.0.x\u002F.claude\u002Fskills\u002Ftest-fixer\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":75},"01M7B5AKHFJW84NSXM8BZBAA9C","mono-repo-integration","https:\u002F\u002Fgithub.com\u002Fapache\u002Fgrails-core\u002Fblob\u002F8.0.x\u002F.claude\u002Fskills\u002Fmono-repo-integration\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":75},"01M7B5AJHPW5ADFJNKM5KVFKSE","hibernate-developer","https:\u002F\u002Fgithub.com\u002Fapache\u002Fgrails-core\u002Fblob\u002F8.0.x\u002F.claude\u002Fskills\u002Fhibernate-developer\u002FSKILL.md",[],[],{"skillNo":95,"name":96,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":75},"01M7B5AHGRTVSKFD4M3KMHWZRZ","grails-8-upgrade","https:\u002F\u002Fgithub.com\u002Fapache\u002Fgrails-core\u002Fblob\u002F8.0.x\u002F.claude\u002Fskills\u002Fgrails-8-upgrade\u002FSKILL.md",[],[],{"skillNo":101,"name":102,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":75},"01M7B5AG2FWXSXCK1ESCBWB2X9","gradle-developer","https:\u002F\u002Fgithub.com\u002Fapache\u002Fgrails-core\u002Fblob\u002F8.0.x\u002F.claude\u002Fskills\u002Fgradle-developer\u002FSKILL.md",[],[]]