Kotlin,generics和一个可能没有任何参数的函数

我试图将这个样板转化成一个非常常见的模式,Kotlin让我感到非常亲近。

我已经构建了一个类作为监听器管理器,如下所示:

class GenericListenerSupport  Unit> { private val listeners = mutableListOf() fun addListener(listener: ListenerFunction) { listeners.add(listener) } fun removeListener(listener: ListenerFunction) { listeners.remove(listener) } fun fireListeners(argument: EventArgumentType) { listeners.forEach { it.invoke(argument) } } } 

它可以使用如下:

 class ExampleWithArgument { private val listenerSupport = GenericListenerSupportUnit>() fun exampleAdd() { listenerSupport.addListener({ value -> System.out.println("My string: "+value)}) } fun exampleFire() { listenerSupport.fireListeners("Hello") } } 

到现在为止还挺好。 但是,如果听众没有理由呢? 或者进一步拉伸,多个参数。

我可以通过这个:

 class ExampleWithNoArgument { private val listenerSupport = GenericListenerSupportUnit>() fun exampleAdd() { listenerSupport.addListener({ System.out.println("I've got no argument")}) } fun exampleFiring() { listenerSupport.fireListeners(null) } } 

但它闻起来,显然这是没有用的多个参数。

有没有更好的方法来解决这个问题? 例如支持这个概念的东西:

 private val listenerSupport = GenericListenerSupportUnit>() 

由于您的GenericListenerSupport声明了一个types参数EventArgumentType并期望它的fun fireListeners(argument: EventArgumentType)它的一个实例,我怀疑你可以支持多个参数干净的方式。 相反,我建议使用一个数据类(这不是多余的代码),作为一个干净和types安全的方式来包装多个值:

 data class MyEvent(val id: String, val value: Double) private val listenerSupport = GenericListenerSupport Unit>() 

至于传递没有价值,你也可以使用Unit ,具有一个值的typesUnit

 listenerSupport.fireListeners(Unit) 

types系统和解析将不允许你传递一个单一的参数,但是,正如@Ruckus T-Boom建议的那样,你可以在没有任何值的情况下,

 fun GenericListenerSupport.fireListeners() = fireListeners(Unit) 

有点偏离主题,但我认为你可以简化types,如果你不需要自定义函数types和(EventArgumentType) -> Unit是足够的:

 class GenericListenerSupport { /* Just use `(EventArgumentType) -> Unit` inside. */ }