https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

Daniele B

08/13/2020, 9:18 PM
Given a data class like this:
Copy code
data class State (
	val aField : String
	val bField : String
	val cField : String
)
I would like to wrap this copy function:
Copy code
wrapperobject.state = wrapperobject.state.copy (aField = aValue, bField = bValue)
inside a custom method like this:
Copy code
wrapperobject.changeState(aField = aValue, bField = bValue)
what would be the code for it? I am not sure how to define the argument of the
changeState
method
s

Shawn

08/13/2020, 9:26 PM
I feel like I’m misunderstanding your question but can’t you just implement it like this?
Copy code
class WrapperObject(var state: State)
  fun changeState(aField: String, bField: String) {
    state = state.copy(aField = aField, bField = bField)
  }
}
d

Daniele B

08/13/2020, 9:29 PM
is there anyway to extract the arguments directly from the State class definition, without having to specify them?
as the arguments could be many, in this way I would have to replicate them in both the class definition and the changeState method
s

Shawn

08/13/2020, 9:32 PM
do you care about restricting the modification of specific fields in the State object?
(I saw there was a cField you didn’t include in the later examples, wasn’t sure if that was intentional)
d

Daniele B

08/13/2020, 9:33 PM
hopefully yes, but I was wondering if Kotlin offered some easy way of matching the arguments of a method to the the properties of a class
I guess copy is a very special function
I wanted to mimic the same behaviour
with the chance also of not specifying all the properties
s

Shawn

08/13/2020, 9:35 PM
unfortunately yes,
copy
on data classes is a unique case
d

Daniele B

08/13/2020, 9:36 PM
ok, I see
thanks
👍 1
4 Views