One of the great features of Kotlin data classes is their copy
method. But using it can become cumbersome very quickly, because you need to repeat the name of the field before and after.
data class Person(val name: String, val age: Int)
val p1 = Person("Alex", 1)
val p2 = p1.copy(age = p1.age + 1) // too many 'age'!
What can KopyKat do?
This plug-in generates a couple of new methods that make working with immutable (read-only) types, like data classes and value classes, more convenient.
copy
Mutable This new version of copy
takes a block as a parameter. Within that block, mutability is simulated; the final assignment of each (mutable) variable becomes the value of the new copy. These are generated for both data classes and value classes.
val p1 = Person("Alex", 1)
val p2 = p1.copy {
age++
}
You can use old
to access the previous (immutable) value, before any changes.
val p3 = p1.copy {
age++
if (notTheirBirthday) {
age = old.age // get the previous value
}
}
Nested mutation
If you have a data class that contains another data class (or value class) as a property, you can also make changes to inner types. Let's say we have these types:
data class Person(val name: String, val job: Job)
data class Job(val title: String, val teams: List<String>)
val p1 = Person(name = "John", job = Job("Developer", listOf("Kotlin", "Training")))
Currently, to do mutate inner types you have to do the following:
val p2 = p1.copy(job = p1.job.copy(title = "Señor Developer"))
With KopyKat you can do this in a more readable way:
val p2 = p1.copy { job.title = "Señor Developer" }
Warning For now, this doesn't work with types that are external to the source code (i.e. dependencies). We are working on supporting this in the future.
Nested collections
The nested mutation also extends to collections, which are turned into their mutable counterparts, if they exist.
val p3 = p1.copy { job.teams.add("Compiler") }
To avoid unnecessary copies, we recommend to mutate the collections in-place as much as possible. This means that forEach
functions and mutation should be preferred over map
.
val p4 = p1.copy { // needs an additional toMutableList at the end
job.teams = job.teams.map { it.capitalize() }.toMutableList()
}
val p5 = p1.copy { // mutates the job.teams collection in-place
job.teams.forEachIndexed { i, team -> job.teams[i] = team.capitalize() }
}
The at.kopyk:mutable-utils
library (documentation) contains versions of the main collection functions which reuse the same structure.
val p6 = p1.copy { // mutates the job.teams collection in-place
job.teams.mutateAll { it.capitalize() }
}
copyMap
Mapping Instead of new values, copyMap
takes as arguments the transformations that ought to be applied to each argument. The "old" value of each field is given as argument to each of the functions, so you can refer to it using it
or introduce an explicit name.
val p1 = Person("Alex", 1)
val p2 = p1.copyMap(age = { it + 1 })
val p3 = p1.copyMap(name = { nm -> nm.capitalize() })
The whole "old" value (the Person
in the example above) is given as receiver to each of the transformations. That means that you can access all the other fields in the body of each of the transformations.
val p4 = p1.copyMap(age = { name.count() })
Note you can use
copyMap
to simulatecopy
, by making the transformation return a constant value.
val p5 = p1.copyMap(age = { 10 })
Note When using value classes, given that you only have one property, you can skip the name of the property.
@JvmInline value class Age(ageValue: Int)
val a = Age(39)
val b = a.copyMap { it + 1 }
copy
for sealed hierarchies
KopyKat also works with sealed hierarchies. These are both sealed classes and sealed interfaces. It generates regular copy
, copyMap
, and mutable copy
for the common properties, which ought to be declared in the parent class.
abstract sealed class User(open val name: String)
data class Person(override val name: String, val age: Int): User(name)
data class Company(override val name: String, val address: String): User(name)
This means that the following code works directly, without requiring an intermediate when
.
fun User.takeOver() = this.copy { name = "Me" }
Equally, you can use copyMap
in a similar fashion:
fun User.takeOver() = this.copyMap(name = { "Me" })
Or, you can use a more familiar copy function:
fun User.takeOver() = this.copy(name = "Me")
Warning KopyKat only generates these if all the subclasses are data or value classes. We can't mutate object types without breaking the world underneath them. And cause a lot of pain.
copy
from supertypes
KopyKat generates "fake constructors" which consume a supertype of a data class, if that supertype defines all the properties required by its primary constructor. This is useful when working with separate domain and data transfer types.
data class Person(val name: String, val age: Int)
@Serializable data class RemotePerson(val name: String, val age: Int)
In that case you can define a common interface which represents the data,
interface PersonCommon {
val name: String
val age: Int
}
data class Person(override val name: String, override val age: Int): PersonCommon
@Serializable data class RemotePerson(override val name: String, override val age: Int): PersonCommon
With those "fake constructors" you can move easily from one to the other representation.
val p1 = Person("Alex", 1)
val p2 = RemotePerson(p1)
copy
for type aliases
KopyKat can also generate the different copy
methods for a type alias.
@CopyExtensions
typealias Person = Pair<String, Int>
// generates the following methods
fun Person.copyMap(first: (String) -> String, second: (Int) -> Int): Person = TODO()
fun Person.copy(block: `Person$Mutable`.() -> Unit): Person = TODO()
The following must hold for the type alias to be processed:
- It must be marked with the
@CopyExtensions
annotation, - It must refer to a data or value class, or a type hierarchy of those.
Using KopyKat in your project
This demo project showcases the use of KopyKat alongside version catalogs.
KopyKat builds upon KSP, from which it inherits easy integration with Gradle. To use this plug-in, add the following in your build.gradle.kts
:
-
Add Maven Central to the list of repositories.
repositories { mavenCentral() }
-
Add KSP to the list of plug-ins. You can check the latest version in their releases.
plugins { id("com.google.devtools.ksp") version "1.7.10-1.0.6" }
-
Add a KSP dependency on KopyKat.
dependencies { // other dependencies ksp("at.kopyk:kopykat-ksp:$kopyKatVersion") }
-
(Optional) If you are using IntelliJ as your IDE, we recommend you to follow these steps to make it aware of the new code.
Enable only for selected types
By default, KopyKat generates methods for every data and value class, and sealed hierarchies of those. If you prefer to enable generation for only some classes, this is of course possible. Note that you always require a @CopyExtensions
annotation to process a type alias.
All classes in given packages
Change the generate
option for the plug-in, by passing options to KSP. The packages should be separated by :
, and you can use wildcards, as supported by wildcardMatch
.
ksp {
arg("generate", "packages:my.example.*")
}
Using annotations
-
Add a dependency to KopyKat's annotation package. Note that we declare it as
compileOnly
, which means there's no trace of it in the compiled artifact.dependencies { // other dependencies compileOnly("at.kopyk:kopykat-annotations:$kopyKatVersion") }
-
Change the
generate
option for the plug-in, by passing options to KSP.ksp { arg("generate", "annotated") }
-
Mark those classes you want KopyKat to process with the
@CopyExtensions
annotation.import at.kopyk.CopyExtensions @CopyExtensions data class Person(val name: String, val age: Int)
Customizing the generation
You can disable the generation of some of these methods by passing options to KSP in your Gradle file. For example, the following block disables the generation of copyMap
.
ksp {
arg("mutableCopy", "true")
arg("copyMap", "false")
arg("hierarchyCopy", "true")
arg("superCopy", "true")
}
By default, the three kinds of methods are generated.
What about optics?
Optics, like the ones provided by Arrow, are a much more powerful abstraction. Apart from changing fields, optics allow uniform access to collections, possibly-null values, and hierarchies of data classes. You can even define a single copy
function which works for every type, instead of relying on generating an implementation for each data type.
KopyKat, on the other hand, aims to be just a tiny step further from Kotlin's built-in copy
. By re-using well-known idioms, the barrier to introducing this plug-in becomes much lower. Our goal is to make it easier to work with immutable data classes.