commonMain.dk.cachet.carp.common.infrastructure.serialization.NotSerializable.kt Maven / Gradle / Ivy
Go to download
Helper classes and base types relied upon by all subsystems. This library does not contain any domain logic.
The newest version!
package dk.cachet.carp.common.infrastructure.serialization
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlin.reflect.KFunction1
/**
* A dummy serializer which can be applied to types that are never expected to be serialized,
* but for which the compiler is trying to generate/retrieve a serializer. E.g., types used as generic type parameters.
* Applying `@Serializable( with = NotSerializable::class )` to those types ensures compilation succeeds,
* without having to actually make them serializable.
*/
object NotSerializable : KSerializer
{
private val exception = SerializationException(
"Types annotated as `@Serializable( with = NotSerializable::class )` are never expected to be serialized. " +
"The serializer is only defined since the compiler does not know this, causing a compilation error."
)
override val descriptor: SerialDescriptor = buildClassSerialDescriptor( "This should never be serialized." )
override fun deserialize( decoder: Decoder ): Nothing = throw exception
override fun serialize( encoder: Encoder, value: Nothing ) = throw exception
}
/**
* Creates a serializer for a class with one type parameter which can safely be ignored during serialization.
* This requires that the type parameter is not used during serialization.
*/
@Suppress( "UNCHECKED_CAST" )
fun ignoreTypeParameters( createSerializer: KFunction1, KSerializer> ): KSerializer =
object : KSerializer
{
val innerSerializer = createSerializer.invoke( NotSerializable as KSerializer )
override val descriptor: SerialDescriptor = innerSerializer.descriptor
override fun serialize( encoder: Encoder, value: T ) =
encoder.encodeSerializableValue( innerSerializer, value )
override fun deserialize( decoder: Decoder ): T =
decoder.decodeSerializableValue( innerSerializer )
}