is it possible to do something like this in kotlin...
# getting-started
y
is it possible to do something like this in kotlin
Copy code
interface ClientEvents {
  ready: () => void;
}

export declare interface Client {

  on<Event extends keyof ClientEvents>(
    event: Event,
    listener: ClientEvents[Event],
  ): this;
  off<Event extends keyof ClientEvents>(
    event: Event,
    listener: ClientEvents[Event]
  ): this;
  emit<Event extends keyof ClientEvents>(
    event: Event,
    ...args: Parameters<ClientEvents[Event]>
  ): boolean;
}
This code is from type script
a
I don’t think so, there’s no structural typing in Kotlin afaik
y
would there be a way to do anything similar
like
Copy code
client.on<ReadyEvent> { c -> {
}
@August Lilleaas
a
not sure exactly what you’re asking, but if I understand you correctly, then yes, it’s possible to specify the types for lambda arguments 🙂
y
so i am trying to create an event listener system where once i want to use client.on to recieve the event
a
you could create an inline extension function with a reified type for the event. That way, you can use the type of the event to run the code you want
so, instead of onFooEvent, onBarEvent, etc, you can use a generic type and call on<FooEvent>, on<BarEvent>, etc
y
ah i see
thank you for the help
a
(it doesn’t have to be an extension function, by the way)
y
can you give me a ruff example please
a
what are you trying to do, and what errors are you getting?
ah, I see the problem now. The type of the event needs to define the type of the lambda
y
yeah
Copy code
inline fun <reified T : Event> EvenTester.on(
    crossinline consumer: suspend EventListener.(T) -> Unit
) {

}
does this look right?
a
you can use typealiases for the events themselves. After all, the only thing the type needs to indicate, is the type of the lambda handlers
y
how do typealiases work
a
actually, that won’t work, as typealiases are subject to type erasure even for reified types
y
oh ok
a
I’m not an expert, but it seems to me that the only way to do this in Kotlin is to have a function for each event type
y
ok
will try that out and let you know if it works