`interface Foo<T> { fun bar(x: Any): Boolean...
# announcements
m
interface Foo<T> { fun bar(x: Any): Boolean { ... } }
- is there some way to return true from bar if x is instance of T?
s
An instance/object can never have the type
T?
. It will have the type
T
or its value is
null
.
d
Not without reification.
s
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
Copy code
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
Copy code
inline fun <reified T> Foo<T>.bar(x: Any): Boolean {
     return x is T
}
Do you actually need the polymorphism?
m
well what I really want is something like:
Copy code
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
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
.
Copy code
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>