Kotlin recall problem
I have these methods declared in Java libraries:
Engine.java:
public <T extends EntitySystem> T getSystem(Class<T> systemType)
Entity.java:
public <T extends Component> T getComponent(Class<T> componentClass)
Now I am using these LOT methods and I would really like to use MyComponent::class
(i.e. kotlin display) instead of the more verbose one javaClass<MyComponent>()
.
My realization EntitySystem
and Component
written in Kotlin.
So, I thought I'd create extension functions that take KClasses
instead, but I'm not really sure how to get them to work.
Something along the lines ...
public fun <C : Component> Entity.getComponent(type: KClass<out Component>): C {
return getComponent(type.javaClass)
}
But this does not work for several reasons: the compiler says that the type inference failed because it javaClass
returns Class<KClass<C>>
. And I need to Class<C>
. I also don't know how to make the method appropriately generic.
Can anyone help me create these methods?
source to share
You should use the extension property java
instead javaClass
.
Additionally, you can improve your API with parameters like reified and rewrite your code like this:
public inline fun <reified C : Component> Entity.getComponent(): C {
return getComponent(C::class.java)
}
source to share
In current Kotlin (1.0), the code will be simpler:
public inline fun <reified C : Component> Entity.getComponent(): C {
return getComponent(C::class)
}
And you can call:
val comp: SomeComponent = entity.getComponent()
Where type inference will be performed, validate the generic type parameter (including any nested shared parameters) and invoke a method that then uses the type parameter as a reference to the class.
source to share