nyxcode
07/20/2017, 6:07 PMinterface SerializationAdapter<T : Any> {
fun serialize(obj: T, output: ByteBuf)
fun deserialize(input: ByteBuf): T
}
data class PacketDeclaration<T : Packet>(val id: Int,
val clazz: KClass<T>,
val serializer: SerializationAdapter<T>)
interface PacketRegistry {
fun <P : Packet> resolve(clazz: KClass<P>): PacketDeclaration<P>
}
fun serialize(byteBuf: ByteBuf, packet: Packet) {
val registry = ...
val dec = registry.resolve(packet::class)
dec.serializer.serialize(packet, byteBuf)
// ^^ Out-projected type 'SerializationAdapter<out Packet>' prohibits the use of 'public abstract fun serialize(obj: T, output: ByteBuf): Unit defined in de.nyxcode.dmn.protocol.SerializationAdapter
}
Any recommendations?diesieben07
07/20/2017, 6:11 PM<T : Packet>
to serialize
and make packet
a T
. Then add a parameter KClass<T>
. Then make a 2nd version of serialize:
inline fun <reified T : Packet> serialize(buf: ByteBuf, packet: T) = serialize(buf, packet, T::class)
.diesieben07
07/20/2017, 6:12 PMserialize
is called with known values of T
. If at the call-site for serialize
you just have a Packet
, then this won't help.nyxcode
07/20/2017, 6:20 PMnyxcode
07/20/2017, 6:21 PM(registry.resolve(msg::class) as PacketDeclaration<Packet>).serializer.serialize(msg, out)
diesieben07
07/20/2017, 6:22 PMnyxcode
07/20/2017, 6:22 PMdiesieben07
07/20/2017, 6:22 PMgroostav
07/20/2017, 6:55 PMOut-projected type 'SerializationAdapter<out Packet>' prohibits the use of 'public abstract fun serialize(obj: T, output: ByteBuf): Unit defined in de.nyxcode.dmn.protocol.SerializationAdapter
this is a covariance warning, Its akin to you trying to writing
interface Vehicle; class Car: Vehicle; class Truck: Vehicle
val list: ArrayList<Vehicle> = newCarList() //returns ArrayList<Car>
list.add(new Truck()) //blam
If you change to
val list: ArrayList<out Vehicle> = ...
then the line
list.add(new Truck())
will fail with the same compiler error your seeing.
The type system is trying to tell you that it cannot be certain T is a Packet, and thus passing in a packet might cause heap pollution.groostav
07/20/2017, 6:57 PMassert(clazz.isInstance(paramOrReturnValue))
nyxcode
07/20/2017, 7:16 PM