is there a way to make `ifEmpty` return statement ...
# serialization
h
is there a way to make
ifEmpty
return statement work with
Json.encodeToString
? If the return type lambda of
ifEmpty
is different than original variable Kotlin resolves type to
Any
, causing
kotlinx.serialization.SerializationException: Serializer for class 'Any' is not found.
I want to do
Copy code
Json.encodeToString(
                myVariable.ifEmpty { ErrorResponse(404, "Path not found.") }
            )
myVariable
is a
List
with a different
data class
than ErrorResponse, e.g. List<Person>. I have marked both data classes as Serializable.
l
Copy code
val PathNotFound: ErrorResponse = ErrorResponse(404, "Path not found.")

val json = if (myVariable.isNotEmpty()) {
    Json.encodeToString(myVariable)
} else {
    Json.encodeToString(PathNotFound)
}
h
Yeah that's similar to my current approach. Was just curious if it could be done with
ifEmpty {}