Home

Awesome

NoCopy Compiler Plugin CI Maven Central

<img src="plugins/idea-plugin/src/main/resources/META-INF/pluginIcon.svg" alt="" width="200" /> A Kotlin compiler plugin that removes the `copy` method from data classes and enables using them as value-based classes.

Usage

Include the gradle plugin in your project and apply @NoCopy to your data class.

@NoCopy

@NoCopy prevents the kotlin compiler from generating the copy method:

@NoCopy
data class User(val name: String, val phoneNumber: String)
User("Ahmed", "+201234567890").copy(phoneNumber = "Happy birthday!") // Unresolved reference: copy

Why? I hear you ask.

The copy method of Kotlin data classes is a known language design problem, normally, you can't remove it, you can't override it, and you can't document it.

Why would you want to do that? Well, there are a couple of reasons:

Consider something like this:

data class User private constructor(val name: String, val phoneNumber: String) {
    companion object {
        fun of(name: String, phoneNumber: String): Either<UserException, User> {
            return if (bad) {
                exception.left() //You can throw an exception here if you like instead.
            } else {
                User(name, phoneNumber).right()
            }
        }
    }
}

It would look like all instances of User must be valid and can't be bad, right?

Wrong:

User.of("Ahmed", "+201234567890").copy(phoneNumber = "Gotcha")

copy can bypass all the validations of your data class, it breaks your domain rules!

For more detailed explanation, check out this article.

Installation

Using plugins DSL

plugins {
  id "dev.ahmedmourad.nocopy.nocopy-gradle-plugin" version "1.5.0"
}

Using legacy plugin application

buildscript {
    repositories {
        mavenCentral()
        // Or
        maven { url "https://plugins.gradle.org/m2/" }
    }
    dependencies {
        classpath "dev.ahmedmourad.nocopy:nocopy-gradle-plugin:1.5.0"
    }  
}
// For each module that needs to use the annotations
apply plugin: 'dev.ahmedmourad.nocopy.nocopy-gradle-plugin'

IDE Support

Caveats

Versions

Kotlin VersionNoCopy Version
1.9.201.5.0
1.5.01.4.0
1.4.321.3.0
1.4.201.2.0
1.4.01.1.0
1.3.721.0.0

License

Copyright (C) 2020 Ahmed Mourad

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.