https://kotlinlang.org logo
#arrow
Title
# arrow
b

Benoît

08/31/2022, 2:11 PM
Hey guys, what's the best way to deal with this error? Thanks
j

Javier

08/31/2022, 2:16 PM
If Nel is not serializable you can create a custom serializer for it
in the custom serializer part you can choose among multiple ways to solve it
s

simon.vergauwen

08/31/2022, 2:48 PM
We should support these things from a common module, but it probably belongs in a separate repository (?) 🤔 @Benoît you should be able to delegate to
List.serializer
j

Javier

08/31/2022, 2:49 PM
It can be a good idea to have an additional artifact with arrow serializers so we haven't to depend on serialization dependency on arrow as Simon said
b

Benoît

08/31/2022, 2:49 PM
Thanks to both of you for your answers, I was thinking of doing this manually yes, was just wondering first if there was an already existing NelSerializer somewhere that I had missed
t

than_

08/31/2022, 3:07 PM
for serialization of (not just) arrow datatypes I have this handy interface:
Copy code
interface IsoSerializer<ENTITY, SURROGATE> : KSerializer<ENTITY> {

    val surrogateSerializer: KSerializer<SURROGATE>
    val iso: Iso<ENTITY, SURROGATE>

    override fun deserialize(decoder: Decoder): ENTITY =
        decoder.decodeSerializableValue(surrogateSerializer).let(iso::reverseGet)


    override val descriptor: SerialDescriptor
        get() = surrogateSerializer.descriptor

    override fun serialize(encoder: Encoder, value: ENTITY) {
        encoder.encodeSerializableValue(surrogateSerializer, iso.get(value))
    }

    companion object {
        inline operator fun <ENTITY, reified SURROGATE> invoke(
            iso: Iso<ENTITY, SURROGATE>,
            surrogateSerializer: KSerializer<SURROGATE>,
        ) = object : IsoSerializer<ENTITY, SURROGATE> {
            override val surrogateSerializer = surrogateSerializer
            override val iso = iso
        }
    }
}
here you can easily serialize anything by just providing a serializable surrogate type and an iso between your type and the surrogate
Copy code
class NelSerializer<T>(elementSerializer: KSerializer<T>) :
    IsoSerializer<NonEmptyList<T>, List<T>> by IsoSerializer(Nel.listIso(),
        ListSerializer(elementSerializer))

fun <T> NonEmptyList.Companion.listIso(): Iso<NonEmptyList<T>, List<T>> = Iso(
    get = ::identity,
    reverseGet = { if (it is Nel<T>) it else Nel.fromListUnsafe(it) }
)
b

Benoît

09/01/2022, 5:47 PM
Amazing! Thanks a lot @than_
38 Views