Specify a Limited Set of Types Allowed for Kotlin Generics

1.1k views Asked by At

Context

I'm building a Flutter application where I need to use some 3rd party library that only works with the native platform. For this, I'm using en EventChannel to get recurring information.

As Flutter and native code can't ensure the types between their communication (the communication methods explicitly define dynamic for the response), I'm trying to add a wrapper of the EventChannel.StreamHandler class, where I could limit the types of that class to match only the ones allowed by flutter.

What I've done so far?

abstract class EventChannelHandler<T> : EventChannel.StreamHandler {
    protected abstract val childClassname: String
    
    private var eventSink: EventChannel.EventSink? = null
    
    override fun onListen(arguments: Any?, eventSink: EventChannel.EventSink?) {
        this.eventSink = eventSink
    }
    
    override fun onCancel(arguments: Any?) {
        eventSink = null
    }
    
    fun add(value: Option<T>) {
        val flutterValue = value.getOrElse { null }
        
        eventSink?.success(flutterValue)
    }
}

This is a base class for some data, and those data would use the above class the following way:

class SpecificData1EventChannelHandler : EventChannelHandler<Int>()
class SpecificData2EventChannelHandler : EventChannelHandler<Double>()
class SpecificData3EventChannelHandler : EventChannelHandler<String>()

Problem

As we can see above, using generics, it allows any kind of type, which doesn't solve my problem.

Final Question

How can I ensure my wrapper class only accepts a specific set of predefined types so that my add function only handle/deliver types that Flutter can understand?

OBS: I'm aware of Pigeon, but I won't use it since it's not stable.

0

There are 0 answers