Marian Schubert
08/28/2019, 7:51 PMinterface Foo<T> { fun bar(x: Any): Boolean { ... } }
- is there some way to return true from bar if x is instance of T?streetsofboston
08/28/2019, 7:53 PMT?
. It will have the type T
or its value is null
.streetsofboston
08/28/2019, 7:54 PM?
is your question-mark 🙂Dominaezzz
08/28/2019, 7:54 PMstreetsofboston
08/28/2019, 7:54 PMDominaezzz
08/28/2019, 7:57 PMinterface Foo<T> {
inline fun <reified T> bar(x: Any): Boolean {
return x is T
}
}
doesn't work, as @streetsofboston said.
next best thing is
inline fun <reified T> Foo<T>.bar(x: Any): Boolean {
return x is T
}
Dominaezzz
08/28/2019, 7:57 PMMarian Schubert
08/28/2019, 8:20 PMinterface Handler<C, R> { fun handle(c: C): R }
then I want Spring to inject all classes which implement that interface, and loop over them and check which class actually handles x's class, and then call foundHandler.handle(x)
Marian Schubert
08/28/2019, 8:22 PMdoesHandle
method into that interface which will do something like x is C
streetsofboston
08/28/2019, 8:30 PMC
parameter in the interface definition, x is C
won’t work. You can’t reify it.
But, you could examine the class of `x`: x::class
.
interface Handler<C, R> {
val classOfC: KClass<out C>
...
}
...
class TestHandler : Handler<InputData, OutputData> {
override val classOfC = InputData::class
...
}
And use classOfC
to check wether something is of the desired type in the other overridden methods of TestHandler.
Like Dominic said, if you don’t need polymorphism, use a reified generic type parameter on an extension function for Handler<C, R>