https://kotlinlang.org logo
#reflect
Title
# reflect
a

albertgao

01/23/2018, 5:26 AM
How to check whether the type of objects inside a
List<*>
is a kotlin official class or my own class, I currently check its name:
paramName.substring(24).removeSuffix(">")
, so
"kotlin.collections.List<nz.salect.objJSON.Lesson>"
will become
"nz.salect.objJSON.Lesson"
, and then I can verify whether it
startsFrom("kotlin")
or not. What’s a better way to do this?
u

udalov

01/23/2018, 11:44 AM
KType.arguments
a

albertgao

01/23/2018, 12:26 PM
@udalov Thanks! I solved this via this
param.type.arguments[0].type?.classifier as KClass<*>
u

udalov

01/23/2018, 12:27 PM
Beware of the fact that type's classifier may not be a class, e.g.
Copy code
fun <T> foo(): List<T>
here
List<T>
is a list of
T
, which is not a
KClass
and therefore will crash with ClassCastException
👍 1
a

albertgao

01/23/2018, 11:09 PM
@udalov Thanks for the reply, do you mean that I should try catch this
as
cast to handle the potential
ClassCastException
?
u

udalov

01/24/2018, 11:25 AM
No. It's never a good idea to catch
ClassCastException
. What I'm saying is that if this situation (type variables) is possible in your use case, you should handle it by inspecting the type of the returned classifier.
KType.classifier
returns
KClassifier
, which has exactly two subclasses:
KClass
and
KTypeParameter
. So if this is possible in your use case, you should have code like
Copy code
val type = param.type.arguments.first().type
when (type.classifier) {
    is KClass<*> -> ...
    is KTypeParameter -> ...
    else -> throw UnsupportedOperationException()
}
Or, a completely different approach, which I suggested in another thread, is to use
jvmErasure
which always gives the
KClass
but loses type information about generics which might be valuable in your use case (again, I don't know what you're using this for, but it might be better one way or the other)
👍 1
2 Views