Making custom adapters

Making custom adapter is very easy. Unless it conforms to SCALE codec principles.

This might be very useful if you want to step out of SCALE's incremental way of serialization.

So let's assume we have a next type:

data class MyCustomType(
    val string: String,
    val int: Int32
)

To make a custom adapter, you could make an adapter like this to reverse variables serialization:

class MyCustomTypeAdapter(
    private val adapterResolver: ScaleCodecAdapterProvider
): ScaleCodeAdapter<MyCustomType> {
    override fun read(
        reader: ByteArrayReader, 
        type: KType, 
        annotations: List<Annotation>
    ): MyCustomType {
        val int = adapterResolver.findAdapter<Int32>().read(reader, Int32::class, listOf())
        val string = adapterResolver.findAdapter<String>().read(reader, String::class, listOf())
        
        return MyCustomType(string, int)
    }
    
    override fun write(
        obj: MyCustomType, 
        type: KType, 
        annotations: List<Annotation>
    ): ByteArray {
        adapterResolver.findAdapter<Int32>().write(obj.int, Int32::class, listOf())
        +
        adapterResolver.findAdapter<String>().write(obj.int, String::class, listOf())
    }
}

Don't worry about ByteArrays. It's just how our codec works. With your custom data container it might be literally everything. It will be just converted to byte array for our convenience.

And then add this to provider like that:

val provider: ScaleCodecAdapterProvider
provider.setAdapter(MyCustomTypeAdapter(), MyCustomType::class)

Feel free to play with custom adapters as much as you want.

Last updated