https://kotlinlang.org logo
Title
m

Marian Schubert

08/28/2019, 7:51 PM
interface Foo<T> { fun bar(x: Any): Boolean { ... } }
- is there some way to return true from bar if x is instance of T?
s

streetsofboston

08/28/2019, 7:53 PM
An instance/object can never have the type
T?
. It will have the type
T
or its value is
null
.
d

Dominaezzz

08/28/2019, 7:54 PM
Not without reification.
s

streetsofboston

08/28/2019, 7:54 PM
Hmm… sorry, the last
?
is your question-mark 🙂
😄 1
✔️ 1
^^^ What Dominic said, and that won’t work with class and interface definitions. Reification works only with function definitions and extension-properties
d

Dominaezzz

08/28/2019, 7:57 PM
interface 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
}
Do you actually need the polymorphism?
m

Marian Schubert

08/28/2019, 8:20 PM
well what I really want is something like:
interface 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)
so I thought I'll add
doesHandle
method into that interface which will do something like
x is C
s

streetsofboston

08/28/2019, 8:30 PM
If you need to put the generic
C
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>