albertgao
01/23/2018, 5:26 AMList<*> 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?udalov
KType.argumentsalbertgao
01/23/2018, 12:26 PMparam.type.arguments[0].type?.classifier as KClass<*>udalov
fun <T> foo(): List<T>
here List<T> is a list of T, which is not a KClass and therefore will crash with ClassCastExceptionalbertgao
01/23/2018, 11:09 PMas cast to handle the potential ClassCastException?udalov
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
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)