Skip to content

Generics are not cared about #2

@UserTeemu

Description

@UserTeemu

The event bus doesn't care about generics. I am not sure if this is an issue, or if it is intended.
Let's explain with a demo:

Code:

import me.kbrewster.eventbus.Subscribe
import me.kbrewster.eventbus.eventbus
import me.kbrewster.eventbus.invokers.LMFInvoker

object Main {
    private val eventBus = eventbus {
        invoker { LMFInvoker() }
        exceptionHandler { exception -> exception.printStackTrace()  }
    }.also {
        with(it) {
            register(Subs())
        }
    }

    @JvmStatic
    fun main(args: Array<String>) {
        println("Testing a string...")
        eventBus.post(ObjectContainer("I like candy."))
        println()
        println("Testing an int...")
        eventBus.post(ObjectContainer(1234567))
    }
}

class Subs {
    @Subscribe
    fun processString(container: ObjectContainer<String>) {
        println("Here is a string: ${container.event}")
    }

    @Subscribe
    fun processInt(container: ObjectContainer<Int>) {
        println("Here is an int: ${container.event}")
    }
}

data class ObjectContainer<T>(val event: T)

Output:

Testing a string...
Here is a string: I like candy.

Testing an int...
Here is an int: 1234567
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Number
	at path.to.randomkotlinprogram.Subs.processInt(Main.kt:35)
	at me.kbrewster.eventbus.EventBus$Subscriber.invoke(eventbus.kt:29)
	at me.kbrewster.eventbus.EventBus.post(eventbus.kt:98)
	at path.to.randomkotlinprogram.Main.main(Main.kt:20)
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
	at path.to.randomkotlinprogram.Subs.processString(Main.kt:30)
	at me.kbrewster.eventbus.EventBus$Subscriber.invoke(eventbus.kt:29)
	at me.kbrewster.eventbus.EventBus.post(eventbus.kt:98)
	at path.to.randomkotlinprogram.Main.main(Main.kt:23)

Those two exceptions are caused by this issue (or maybe intended "feature"). The subscriber is called with an instance of ObjectContainer without noting the wanted generic type of the subscriber.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions