Hi! I encountered a strange generic issue related ...
# decompose
p
Hi! I encountered a strange generic issue related to
StateKeeper.consume
function. That's how my current variant works and builds fine:
Copy code
inline fun <reified T> StateKeeper.test1() {
    val value: T? = consume("key", serializer())
}
However, I now need to pass a custom serializer, so I tried updating the function as follows:
Copy code
inline fun <reified T> StateKeeper.test2(
    serializer: KSerializer<T> = serializer(),
) {
    val value: T? = consume("key", serializer)
}
However, I now have a build issue related to the
consume
function having the
T : Any
restriction. If I add the same restriction to my function, I won't be able to use it with optional types, even though the old version works fine with them and serializes properly. Am I missing some knowledge about generic usage? Is the
T : Any
restriction really needed for
consume
?
a
I have no idea why the first example works. Looks like an edge case in compiler or kotlinx-serialization. It works probably due to type erasure, and a nullable
KSerializer
is able to deserialize non-nullable values. I don't remember details why it was made
T : Any
. But you just don't need a nullable serializer, you can use non-nullable and it handles nulls internally anyway. Keep in mind that the return type of the
consume
function must be nullable anyway, because there might be no saved value. E.g. it doesn't make sense to be able to write both of the following:
Copy code
val s1: String? = stateKeeper.consume("key", serializer<String?>())
stateKeeper.register("key", serializer<String?>()) { null }

val s2: String? = stateKeeper.consume("key", serializer<String>())
stateKeeper.register("key", serializer<String>()) { null }
I will think about it and maybe allow
T
in the next major release, but unlikely.