I have the following function:
inline fun <reified T> create(preference: Preference<T>, title: String = ""): DebugOption{
val type = when (preference) {
is Preference<String> -> Type.STRING
is Preference<Boolean> -> Type.BOOLEAN
else -> Type.STRING
}
return DebugOption(type, preference, displayTitle = StringModel(title))
}
I was expecting to be able to easily perform this 'is' check, since the generic type is reified, but I am still getting a compiler error:
Cannot check for instance of erased type: Preference<String>
Cannot check for instance of erased type: Preference<Boolean>
So I am confused how am I misusing 'reified' / what am I missing here. Is there a problem with using reified generic types as the type parameter of another class?
The problem is that
ischecks the runtime type ofpreference, and the runtime type ofpreferenceisn't available until all the generic type information has been erased. Reified types are not magic, after all.What you can do instead, is check
Tinstead, since as you said,Tis indeed reified.But note that if
Preferenceis covariant (likeList) or contravariant, this might not work as you expect in some cases. For example:In this case,
Tis inferred to beAny, sotypewill be assignedType.STRING. If that is unexpected to you, and you wantType.BOOLEANinstead, you might want to use another way to check a preference's type, rather than reified types, as this cannot be determined at compile time.