KotlinDataClassNoCopy
Suppress the generation of the
copy()
function in Kotlin’sdata class
.
Kotlin’s data class
is a really cool feature that automatically generates useful functions like equals
, hashCode
, copy
, and componentN
.
However, sometimes you want all the benefits of the data class
but not the copy()
function.
For example, code like this:
data class Adult private constructor(
val age: Int,
val name: String,
) {
companion object {
fun from(name: String): Adult {
return if (name == "Zohn") {
Adult(age = 49, name = "Zohn")
} else {
error("No one allowed except \"Zohn\".")
}
}
}
}
This data class
only accepts the name “Zohn”, but the auto-generated copy()
function allows you to bypass this condition and create a new instance.
val Zosh = Adult.from("Zohn").copy(age = 21, name = "Zosh")
With this library, the copy()
function of data class
is no longer accessible.
Unresolved reference: copy
Download ![maven-central](https://camo.githubusercontent.com/0673fa2bdea2c5e71f6a2b5bc1671334334d98dd93549ce0afe1bb18e7599f44/68747470733a2f2f696d672e736869656c64732e696f2f6d6176656e2d63656e7472616c2f762f6c616e642e73756e6762696e2e6b6f746c696e2e64617461636c6173732e6e6f636f70792f6b6f746c696e2d64617461636c6173732d6e6f636f70792d677261646c65)
- Kotlin 1.8.20:
1.0.3
plugins {
id("land.sungbin.kotlin.dataclass.nocopy.plugin") version "$version"
}
Usage
Apply the @NoCopy
annotation to data class
.
@NoCopy
data class Adult private constructor(
val age: Int,
val name: String,
) {
companion object {
fun from(name: String): Adult {
return if (name == "Zohn") {
Adult(age = 49, name = "Zohn")
} else {
error("No one allowed except \"Zohn\".")
}
}
}
}
You can configure plugin with properties on the nocopy
extension.
nocopy {
// Whether NoCopy is enabled
enabled.set(true) // default
// Whether to show verbose logging
verbose.set(false) // default
}
Caveats
- Interaction with IDEs is not yet supported. (there is no public API to handle this)
- This library uses the Kotlin Compiler Plugin, which is still unstable.
License
This project is licensed under the MIT License. Please refer to the LICENSE file for details.