Currently, I have an interface `Foo` as a base for...
# getting-started
m
Currently, I have an interface
Foo
as a base for all classes that can emit events, it has a function
on
that is used to register a handler for that event. The event has a generic type which specifies on which class can the event be emitted. I'd like to override the
on
function to accept events that can be emitted from
Bar
(and its subclasses) and the also keep the type of the target of
handler
the class that the
on
function is called on. Is there any way to implement this without adding a type argument to the
Foo
class itself?
Copy code
interface Foo {
    fun on(signal: Event<in Foo>, handler: Foo.() -> Unit)
}

class Bar : Foo {
    override fun on(signal: Event<in Bar>, handler: Bar.() -> Unit) {
        // ...
    }
}

sealed interface Event<T : Foo> { /* ... */ }

data object SomeEvent : Event<Foo> { /* ... */ }

data object AnotherEvent : Event<Bar> { /* ... */ }
r
No, because you can always cast a
Bar
to a
Foo
, so it needs to accept anything
Foo
can.
Subclasses can only widen inputs and narrow outputs, not the other way around.
👍 1
m
Oh, I kinda though that it would widen it, but ye, I get it now, thanks!