Home > Software engineering >  Kotlin equivalent for "with" keyword in C# (data class)
Kotlin equivalent for "with" keyword in C# (data class)

Time:11-25

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://docs.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.

CodePudding user response:

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.

CodePudding user response:

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,
)

CodePudding user response:

See https://kotlinlang.org/docs/data-classes.html#copying

Use the copy() function to copy an object, allowing you to alter some of its properties while keeping the rest unchanged. The implementation of this function for the User class above would be as follows:

fun copy(name: String = this.name, age: Int = this.age) = User(name, age)

Copied!

You can then write the following:

val jack = User(name = "Jack", age = 1)
val olderJack = jack.copy(age = 2)
  • Related