Reputation: 352
In C# there is a kind of class that is called "record" which is more or less the same as a "data" class in Kotlin.
When using a record in C# you can use the keyword "with" to create a new instance of the your record with some properties set to specific values (see https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/with-expression )
I was wondering if there is a similar way to do it in kotlin ? I cannot find anything regarding that, and the way I do it for now is by defining function that do the job, but it can be kind of boilerplate sometimes, and using data class is supposed to avoid me that boilerplate work.
Also I'd prefer to avoid using "var" properties (to have immutable instances), hence my question.
Upvotes: 3
Views: 832
Reputation: 1311
Kotlin has Data classes, that are close to C# records. As you can see from the Kotlin documentation:
It is not unusual to create classes whose main purpose is to hold data. In such classes, some standard functionality and some utility functions are often mechanically derivable from the data. In Kotlin, these are called data classes and are marked with data:
data class User(val name: String, val age: Int)
The compiler automatically derives the following members from all properties declared in the primary constructor:
equals()/ hashCode() pair toString() of the form "User(name=John, age=42)" componentN() functions corresponding to the properties in their order of declaration. copy() function (see below).
The last line shows that the compiler automatically generates a copy
function for a Data class, and this is what you are looking for
Again from the documentation, the usage would be:
Use the copy() function to copy an object, allowing you to alter some of its properties while keeping the rest unchanged. [...] You can then write the following:
val jack = User(name = "Jack", age = 1) val olderJack = jack.copy(age = 2)
Upvotes: 2
Reputation: 1910
With a data class, you can use the copy
method:
val someData = SomeClass(a = 1, b = 2)
val modifiedData = someData.copy(b = 0) // modifiedData = SomeClass(a = 1, b = 0)
See the official data class documentation.
Upvotes: 2
Reputation: 28332
Do you mean something like copy()
function that is auto-generated for data classes?
fun main() {
val foo1 = Foo("foo", 5)
val foo2 = foo1.copy(value1 = "bar")
val foo3 = foo2.copy(value2 = 10)
}
data class Foo(
val value1: String,
val value2: Int,
)
Upvotes: 1