Moshi PolymorphicJsonAdapter for nested sealed classes maybe not generating adapter correctly - kotlin

When a subclass of a sealed class has a property that is a subclass of a different sealed class the generated adapter does not recognize the correct types. For example:
Given the following classes:
sealed class Operation(
val id: Long,
val params: Params?,
) {
sealed class Params()
}
sealed class SpecialOperation(
id: Long,
params: SpecialOperation.Params?,
) : Operation(id, params) {
class Params : Operation.Params()
}
The generated adapter for the SpecialOperation class constructs an instance of Operation.Params instead of an instance of SpecialOperation.Params which then throws an exception: Type mismatch: inferred type is Operation.Params? but SpecialOperation.Params? was expected.
I was able to work around this behavior by making the properties from the super sealed class Operation open and overriding them in the subclass SpecialOperation like the following:
sealed class Operation(
open val id: Long,
open val params: Params?,
) {
...
}
sealed class SpecialOperation(
override val id: Long,
override val params: SpecialOperation.Params?,
) : Operation(id, params) {
...
}
In this situation shouldn't the generated adapter check the type of the constructor argument instead of the type of the property on the superclass as one is a subtype of the other?

Related

Kotlin - make multiple sealed classes have common set of "base" subclasses, but each could still add it's specific ones

This question has a wider scope than Extract common objects from sealed class in kotlin and Android - How to make sealed class extend other sealed class? so it's not a duplicate of these
I have multiple sealed classes that represent results of various API calls. Each of these calls has a common set of expected results (success, network error, unexpected error), but each could introduce it's own result types (like 'user not found' or 'wrong ID').
To avoid copying same subclasses to each of sealed class, I want to create a "base" type that includes all common result types, while each sealed class could add it's specific subclasses:
interface BaseApiCallResult {
data class Success(val data: String) : BaseApiCallResult
data class UnexpectedError(val error: Throwable) : BaseApiCallResult
data class NetworkError(val error: ApolloException) : BaseApiCallResult
}
sealed class ApiCallResult1 : BaseApiCallResult {
data class WrongID(val id: Int) : ApiCallResult1()
}
sealed class ApiCallResult2 : BaseApiCallResult {
data class UserDoesNotExist(val userid: Long) : ApiCallResult2()
}
sealed class ApiCallResult3 : BaseApiCallResult {
data class NameAlreadyTaken(val name: String) : ApiCallResult3()
}
the problem is that subclasses in "base" cannot be treated as "child" classes:
fun apiCall1(): ApiCallResult1 {
// won't compile, since BaseApiCallResult.UnexpectedError is not ApiCallResult1
return BaseApiCallResult.UnexpectedError(Exception(""))
}
fun useApi() {
when(val result = apiCall1()) {
is ApiCallResult1.WrongID -> { }
// compile error: Incompatible types
is BaseApiCallResult.Success -> { }
is BaseApiCallResult.UnexpectedError -> { }
is BaseApiCallResult.NetworkError -> { }
}
}
solution from Android - How to make sealed class extend other sealed class? might be applied here, but for big number of sealed classes (I expect I might need several dozen of such classes) it becomes rather hacky
interface BaseApiCallResult {
data class Success(val data: String) : Everything
data class UnexpectedError(val error: Throwable) : Everything
data class NetworkError(val error: ApolloException) : Everything
}
sealed interface ApiCallResult1 : BaseApiCallResult {
data class WrongID(val id: Int) : ApiCallResult1()
}
sealed interface ApiCallResult2 : BaseApiCallResult {
data class UserDoesNotExist(val userid: Long) : ApiCallResult2
}
sealed interface ApiCallResult3 : BaseApiCallResult {
data class NameAlreadyTaken(val name: String) : ApiCallResult3
}
// adding each new sealed interface here seems like a hack
interface Everything : BaseApiCallResult, ApiCallResult1, ApiCallResult2, ApiCallResult3
Additionally, with above solution, every when {...} complains about Everything case not being handled. I could resign from using Everything, but then I have to list all interfaces in each "base" subclass, which is simply terrible:
// just imagine how would it look if there were 30 ApiCallResult classes
interface BaseApiCallResult {
data class Success(val data: String) : BaseApiCallResult, ApiCallResult1, ApiCallResult2, ApiCallResult3
data class UnexpectedError(val error: Throwable) : BaseApiCallResult, ApiCallResult1, ApiCallResult2, ApiCallResult3
data class NetworkError(val error: ApolloException) : BaseApiCallResult, ApiCallResult1, ApiCallResult2, ApiCallResult3
}
Is there a better way to handle this kind of situation ?
You have to separate ApiResult from ApiMethodResult they should not to be relatives.
Kotlin already has type Result and you can use it:
sealed interface ApiCall1Result {
class WrongID : ApiCall1Result
class UserInfo(val userId: Int) : ApiCall1Result
}
fun api1() : Result<ApiCallResult>
fun useApi1() {
val result = api1()
if(result.isFailure) {
handle failure
} else {
val apiResult = result.getOrThrow()
when(apiResult) {
is WrongID -> {}
is UserInfo -> {}
}
}
}
Or you can implement it by your self:
interface ApiResult<in T> {
class Success<T : Any>(val data: T) : ApiResult<T>
class Fail(val error: Throwable) : ApiResult<Any>
}
sealed class ApiCallResult1 {
class WrongID(val id: Int) : ApiCallResult1()
class UserInfo(val id: Int, val name: String) : ApiCallResult1()
}
fun apiCall1(): ApiResult<ApiCallResult1> {
return ApiResult.Fail(Throwable())
}
fun useApi() {
when (val result = apiCall1()) {
is ApiResult.Fail -> {}
is ApiResult.Success -> when (result.data) {
is ApiCallResult1.WrongID -> {}
is ApiCallResult1.UserInfo -> {}
}
}
}
You could create a generic type for the sealed interface, and this type gets wrapped by one additional child class:
interface ApiCallResult<out O> {
data class Success(val data: String) : ApiCallResult<Nothing>
data class UnexpectedError(val error: Throwable) : ApiCallResult<Nothing>
data class NetworkError(val error: ApolloException) : ApiCallResult<Nothing>
data class Other<out O>(val value: O): ApiCallResult<O>
}
Then you can define your other callback types using a specific class as the O type:
data class UserDoesNotExist(val userid: Long)
fun handleApiCallResult2(result: ApiCallResult<UserDoesNotExist>) {
when (result) {
is ApiCallResult.Success -> {}
is ApiCallResult.UnexpectedError -> {}
is ApiCallResult.NetworkError -> {}
is ApiCallResult.Other -> {
// do something with result.value
}
}
}
When you have more than one other case, you can create a sealed interface to be the parent of those other cases, but you'll unfortunately need a nested when to handle them.
When you have no other cases, you can use ApiCallResult<Nothing> as your response type, but you'll unfortunately need to leave a do-nothing {} branch for the Other case. Or you could set up a separate sealed interface like in your long-winded final solution in your question, which is manageable because it would never grow to more than two sealed types.

How to call an abstract method from a Class parameter in Kotlin?

Aim
Have a function Book, which takes one of three Letter classes as argument myClass and then calls 'genericMethod()' from the abstract class which Letter*() has inherited.
Issue
If I try Book(LetterA()).read() I get the following error:
Type mismatch. Required: Class<SampleClassArguments.Alphabet> Found: SampleClassArguments.LetterA
Does Kotlin have any way to achieve this result?
Code
#Test
fun readBookTest() {
Book(LetterA()).read() /*<--error here*/
}
class Book(val myClass: Class<Alphabet>) {
fun read() {
val letterClass = myClass.getConstructor().newInstance()
letterClass.genericMethod(myClass.name)
}
}
class LetterA(): Alphabet()
class LetterB(): Alphabet()
class LetterC(): Alphabet()
abstract class Alphabet {
fun genericMethod(className: String) {
println("The class is: $className")
}
}
You need to define the Class type as covariant with the out keyword so any of the child classes is an acceptable argument:
class Book(val myClass: Class<out Alphabet>)
And when you use it, you need to pass the actual Class, not an instance of the class. You can get the Class by calling ::class.java on the name of the class:
#Test
fun readBookTest() {
Book(LetterA::class.java).read()
}

can I use kotlinx serializer with multiple sealed class levels as parents and a nested invocation?

I am trying to use kotlinx #Serializable and Ive faced this issue:
I have the following classes:
#Serializable
sealed class GrandParent
a second one:
#Serializable
sealed class Parent() : GrandParent() {
abstract val id: String
}
and a third one
#Serializable
data class Child(
override val id: String, ....
): Parent()
I'm needing of grandparent since I use it as a generic type in another class, which happen to also have a reference to the GrandParent class
#Serializable
data class MyContent(
override val id: String,
....
val data: GrandParent, <- so it has a self reference to hold nested levels
...): Parent()
Every time I try to run this I get an error...
Class 'MyContent' is not registered for polymorphic serialization in the scope of 'GrandParent'.
Mark the base class as 'sealed' or register the serializer explicitly.
I am using ktor as wrapper, kotlin 1.5.10. I did this based on https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#registered-subclasses
Any ideas?
You should serialize and deserialize using your sealed class in order for kotlin serialization to "know" to add a discriminator with the right implementation. By default it search for type in the json but you can change it with JsonBuilder:
Json {
classDiscriminator = "class"
}
Here is an example:
#Serializable
sealed class GrandParent
#Serializable
sealed class Parent : GrandParent() {
abstract val id: String,
}
#Serializable
data class Child(
override val id: String,
): Parent()
#Serializable
data class MyContent(
override val id: String,
val data: GrandParent,
): Parent()
fun main() {
val test = MyContent(id = "test", data = Child(id = "child"))
val jsonStr = Json.encodeToString(GrandParent.serializer(), test)
println("Json string: $jsonStr")
val decoded = Json.decodeFromString(GrandParent.serializer(), jsonStr)
println("Decoded object: $decoded")
}
Result in console:
Json string: {"type":"MyContent","id":"test","data":{"type":"Child","id":"child"}}
Decoded object: MyContent(id=test, data=Child(id=child))
encode and decode can also be written like this (but behind the scenes it will use reflections):
val jsonStr = Json.encodeToString<GrandParent>(test)
println("Json string: $jsonStr")
val decoded = Json.decodeFromString<GrandParent>(jsonStr)
println("Decoded object: $decoded")

Proper way to serialize a sealed class with kotlinx-serialization

I am not sure if it is possible yet but i would like to serialize the following class.
#Serializable
sealed class RestResponseDTO<out T : Any>{
#Serializable
#SerialName("Success")
class Success<out T : Any>(val value: T) : RestResponseDTO<T>()
#Serializable
#SerialName("Failure")
class Error(val message: String) : RestResponseDTO<String>()
}
when i try and use it
route(buildRoute(BookDTO.restStub)) {
get {
call.respond(RestResponseDTO.Success(BookRepo.getAll()))
}
}
I get this error:
kotlinx.serialization.SerializationException: Serializer for class
'Success' is not found. Mark the class as #Serializable or provide the
serializer explicitly.
The repo mentioned in the get portion of the route returns a list of BookDTO
#Serializable
data class BookDTO(
override val id: Int,
override val dateCreated: Long,
override val dateUpdated: Long,
val title: String,
val isbn: String,
val description: String,
val publisher:DTOMin,
val authors:List<DTOMin>
):DTO {
override fun getDisplay() = title
companion object {
val restStub = "/books"
}
}
This problem is not a deal breaker but it would be great to use an exhaustive when on my ktor-client.
Serializing sealed classes works just fine. What is blocking you are the generic type parameters.
You probably want to remove those, and simply use value: DTO. Next, make sure to have all subtypes of DTO registered for polymorphic serialization in the SerializersModule.

Share common properties between Kotlin classes

I have 2 (data) classes that almost share the same properties:
data class Foo(
val id: FooId,
val name: String,
... 10+ properties
}
data class NewFoo(
val name: String,
... 10+ properties
}
I just want some syntax sugar magic here: not to repeat 10+ properties. I can make a base sealed class, but you would end up writing even more text (for passing arguments to base class ctor), although you are safer from making a mistake.
Yes, I know I could use composition for this, but here I don't want to, as there might be different 'variants' of the same data.
Am I missing something or this is not possible in Kotlin?
You can use an abstract (or sealed) class with abstract params instead and override them in the constructor of your data class (i.e. without additional passing them into the constructor of the base class).
abstract class Base {
// put commons parameter here
// abstract param needs to be initialized in the constructor of data class
abstract val name: String
// you can define some not-abstract params as well
open lateinit var someOtherParam: String
}
data class Foo1(
override val name: String,
val id: Int,
val someAdditionalParam1: String
) : Base()
data class Foo2(
override val name: String,
val someAdditionalParam2: String,
override var someOtherParam: String
) : Base()