Home > Enterprise >  How to change "val" values in an object withotu changing the definition to "var"
How to change "val" values in an object withotu changing the definition to "var"

Time:06-21

I have a complex Kotlin data class, say something like this:

data class Post(
    val message: Message,
    val dateAndTime: LocalTime,
    val postAuthor: Author?,
    val visitorsVisitedTimes: List<Pair<LocalTime, Author>>
)

and each of Message, LocalTime, ... are different data classes.

I have an object of above Post data class. I want to parse it, access visitorsVisitedTimes field value, for each pair, replace Author object with corresponding postAuthor. I have to make similar changes in the Message object as well.

And I don't want to make changes in the class definition.

One way would be to convert this object into a json string, parse it, make require changes and cast it back to Post::class.java and return it.

I did something like this:

// input is an object of Post::class
var jsonString: String = Gson().toJson(input)
// parse the json string, make required changes
var objectFromJson: Post = Gson().fromJson(jsonString, Post::class.java)
return objectFromJson

But, I'm not sure how to make required changes in the Json string.

How can I do that, if not, is there any other way to do the task?

CodePudding user response:

Create a copy of an object, see https://kotlinlang.org/docs/data-classes.html.

val newPost = post.copy(
    message = post.message.copy(text = "some text"),
    postAuthor = Author(...)
)
  • Related