Daniel De Jesus Rodrigues
11/27/2022, 8:35 PMdata class PostReply(
val author: String,
val body: String,
val replies: List<PostReply> // can be infinitely deep
)
I’ve created one regular data class, and another with serialized annotations. But I cannot think a good way on how to map replies
recursively. I tried that but didn’t work:
fun PostRepliesResponse.toModel() = PostReplies(
//...
replies = replies.map { reply -> reply.toModel() }
)
Can you guys help me?Josh Eldridge
11/27/2022, 8:47 PMPostReplies
and PostRepliesResponse
classes?Daniel De Jesus Rodrigues
11/27/2022, 9:03 PMDaniel De Jesus Rodrigues
11/27/2022, 9:04 PM@SerializedName("")
on fieldsJosh Eldridge
11/27/2022, 9:08 PM.toModel()
look like on the PostReply
class?Daniel De Jesus Rodrigues
11/27/2022, 9:10 PMDaniel De Jesus Rodrigues
11/27/2022, 9:10 PM.toModel()
is a extension to map from PostRepliesResponse
to PostReplies
Daniel De Jesus Rodrigues
11/27/2022, 9:11 PMPostReplies.toResponse()
Josh Eldridge
11/27/2022, 9:13 PMreplies.map { reply -> reply.toModel() }
is trying to call a toModel
as well, but it's called on a separate type, what is the types of the replies
list here? It's hard for me to tell without more context, but it seems like we only defined a single toModel
extension on the top level model but I'm not seeing where we defined a toModel
extension on the inner reply typesDaniel De Jesus Rodrigues
11/27/2022, 9:16 PMreplies
field is a list of PostReplies
. Each reply have a replies field of the same timeDaniel De Jesus Rodrigues
11/27/2022, 9:17 PM.toModel()
recursivelyJosh Eldridge
11/27/2022, 9:19 PMfun PostReplies.toModel(): List<PostReplies> {
if (replies.isNotEmpty()) {
replies.map { reply -> reply.toModel() }
} else {
emptyList<PostReplies>()
}
}
Josh Eldridge
11/27/2022, 9:20 PMJosh Eldridge
11/27/2022, 9:23 PMDaniel De Jesus Rodrigues
11/27/2022, 9:27 PMDaniel De Jesus Rodrigues
11/27/2022, 9:27 PMDaniel De Jesus Rodrigues
11/27/2022, 9:28 PMfun PostRepliesResponse.toModel() = PostReplies(
id = id,
ownerUsername = ownerUsername,
body = body,
tabcoins = tabcoins,
repliesAmount = repliesAmount,
replies = replies.toModel()
)
fun List<PostRepliesResponse>.toModel(): List<PostReplies> {
return this.map {
PostReplies(
id = it.id,
ownerUsername = it.ownerUsername,
body = it.body,
tabcoins = it.tabcoins,
repliesAmount = it.repliesAmount,
replies = it.replies.toModel()
)
}
}
Daniel De Jesus Rodrigues
11/27/2022, 9:28 PMJosh Eldridge
11/27/2022, 9:28 PMJosh Eldridge
11/27/2022, 9:29 PMDaniel De Jesus Rodrigues
11/27/2022, 9:29 PMDaniel De Jesus Rodrigues
11/27/2022, 9:48 PMJosh Eldridge
11/27/2022, 10:33 PM