Is it possible to do something based on a reified ...
# announcements
l
Is it possible to do something based on a reified T parameter being another something? I wanted something like
Copy code
inline fun <reified T> foo() {
    when(T) {
       is Foo -> tFoo()
        is Bar -> tBar()
    }
}
s
You can write
T::class
and go from there (it will return a
KClass<out T>
value)
c
Won’t regular generics work for that?
Copy code
inline fun <T> blah(thing: T) {
    when (thing) {
        is String -> ""
        is Int -> thing + 1
    }
}
I’ve used reified in cases that @streetsofboston pointed out above
s
The original poster may not have an instance of type ‘T’, and must call
foo<MyBar>()
or something similar.
c
Copy code
fun <T> T.blah() {
    when (this) {
        is String -> ""
        is Int -> this + 1
    }
}
Would that be in the same spirit? Sorry might be missing what the usecase would look like
l
I want to fetch a factory for
T
Something like
getFactory<Foo>
s
The function is probably a top/static function
c
Ah gotcha 🙇🏻
s
@LeoColman You can use
T::class.java.isAssignableFrom(Class<*>)
l
I could do that in the JVM, but I wanted to do it in MPP
Perhaps there's something I can do using
T::class
only?
s
Hmmmm… use
KClass<*>.supertypes
to write your own
KClass<*>.isA(KClass<*>)
extension function…
l
Perhaps this could be a suggestion to #C0B8Q383C
l
tl;dr, but would this work for you?
Copy code
inline fun <reified T: A> foo() {
    when(T::class) {
       B::class -> b()
       C::class -> c()
    }
}
I used a case where B and C extends sealed class A but that is not necessary with an else
l
Hmm.. Perhaps that would work, yes
s
This would work if the classes are the same, but not if T is a base class or base interface of B or C
l
I don't think that's the case. This will be used only for specific classes (for now, at least)
s
I really thought this would work
Copy code
inline fun <reified T> factory(): Factory<T> = when(T::class) {
       Int::class -> object : Factory<Int>{override fun create()=1}
       Double::class -> object : Factory<Double>{override fun create()=2.0}
       else -> throw IllegalArgumentException("unknown class")
    }

interface Factory<out G> {
    fun create():G
}
alas it doesn’t https://pl.kotl.in/r0zfH3cm_
l
The factory is converted to
Factory<Any>
. Interesting
I suppose it can be casted if needed