DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

Containers Trend Report: Explore the current state of containers, containerization strategies, and modernizing architecture.

Low-Code Development: Learn the concepts of low code, features + use cases for professional devs, and the low-code implementation process.

E-Commerce Development Essentials: Considering starting or working on an e-commerce business? Learn how to create a backend that scales.

Related

  • Transitioning From Groovy to Kotlin for Gradle Android Projects
  • The Complete Gradle Plugin Tutorial
  • Integrating Java and npm Builds Using Gradle - Groovy or Kotlin DSL
  • Building Pop-Up Compose Notifications in Android Using Kotlin and Compose

Trending

  • Securing REST APIs With Nest.js: A Step-by-Step Guide
  • Understanding the New SEC Rules for Disclosing Cybersecurity Incidents
  • The Top 5 Tools for Automated Front-End Testing
  • Software Architecture Design Patterns for Serverless System
  1. DZone
  2. Coding
  3. Languages
  4. Using Kotlin Extensions in Groovy

Using Kotlin Extensions in Groovy

Dive into two different ways of using extension methods with Kotlin and Groovy, which is particularly useful if you want to use Spock for testing.

Dominik Przybysz user avatar by
Dominik Przybysz
·
Aug. 28, 17 · Tutorial
Like (5)
Save
Tweet
Share
10.1K Views

Join the DZone community and get the full member experience.

Join For Free

Kotlin and Groovy have mechanisms for extending existing classes without using inheritance or decorators. In both languages, the mechanisms are called extension methods. Their source code looks different, but generated bytecode is quite similar. Thanks to that, Groovy is able to use Kotlin extensions just like its own.

Why would I want to use such extensions in Groovy? The main reason is that I want to test my extensions using the best testing framework available for the JVM — Spock Framework.

The code is available here.

Extensions in Kotlin

There are many types of extensions in Kotlin. I decided to focus only on extension functions and properties.

As an example, I extend the java.lang.String class. First, I create an extension function, skipFirst, which skips the first N characters:

fun String.skipFirst(n: Int) = if (length > n) this.substring(n) else ""


Next, I create an extension property answer, which is the Answer to the Ultimate Question of Life, the Universe, and Everything:

val String.answer
    get() = 42


Both extensions are declared in the package com.github.alien11689.extensions, in the file StringExtensions. However, the generated class in the target directory is named StringExtensionsKt , and this is the name that must be used when accessing it from other languages. Specific class names can be forced by the annotation @file:JvmName.

Using Kotlin Extensions in Groovy

There are two ways to use extensions in Groovy (that are supported by good IDEs). First, you can declare the scope where the extensions are available by the use method:

def "should use extension method"() {
    expect:
        use(StringExtensionsKt) {
            input.skipFirst(n) == expected
        }
    where:
        input  | n | expected
        "abcd" | 3 | "d"
        "abcd" | 6 | ""
        ""     | 3 | ""
}

def "should use extension property"() {
    expect:
        use(StringExtensionsKt) {
            "abcd".answer == 42
        }
}


This is acceptable, but it is not very convenient. The second and much better way is to use an extension module definition. The extension module is defined in the file org.codehaus.groovy.runtime.ExtensionModule in the directory src/main/resources/META-INF/services/. The same directory is monitored by ServiceLoader, but the file format is completely different:

moduleName=string-extension-module
moduleVersion=1.0.0
extensionClasses=com.github.alien11689.extensions.StringExtensionsKt


The tests look much better now:

def "should use extension method"() {
    expect:
        input.skipFirst(n) == expected
    where:
        input  | n | expected
        "abcd" | 3 | "d"
        "abcd" | 6 | ""
        ""     | 3 | ""
}

def "should use extension property"() {
    expect:
        "abcd".answer == 42
}
Kotlin (programming language) Groovy (programming language)

Published at DZone with permission of Dominik Przybysz. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Transitioning From Groovy to Kotlin for Gradle Android Projects
  • The Complete Gradle Plugin Tutorial
  • Integrating Java and npm Builds Using Gradle - Groovy or Kotlin DSL
  • Building Pop-Up Compose Notifications in Android Using Kotlin and Compose

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: