I have "Conditional branch result of type ... is implicity cast of Any?" warning when i try to do something like this:
objects?.forEach {
val gson = Gson()
val chatObject = if(it.type == CHAT_TEXT_TYPE) gson.fromJson(it.value, ChatText::class.java) //WARNING
else gson.fromJson(it.value, ChatProduct::class.java) //WARNING
//TEST
if(chatObject is ChatText) Log.e("ChatText: It works!", chatObject.text)
if(chatObject is ChatProduct) Log.e("ChatProduct: It works!", chatObject.name)
}
But finally it works. Is anything wrong with my code? Is it any possibility to remove this warning?
EDIT (as @Xavier Bouclet suggested - warning disappeared)
val chatObject = when (it.type)
{
CHAT_TEXT_TYPE -> gson.fromJson(it.value, ChatText::class.java)
CHAT_PRODUCT_TYPE -> gson.fromJson(it.value, ChatProduct::class.java)
else -> gson.fromJson(it.value, Any::class.java)
}
The warning is telling you that you've returned different types in your branches, and that the variable you're assigning will be inferred to be their first common supertype, which in this case is Any?
. This is not the way you usually use the if-else
expression, you usually return the same type from both branches. The IDE is warning you because what you're doing is usually accidental.
If you're going to check the type of the result later for the actual types you're using anyway, you're probably fine with your code.
To remove the warning, you can either suppress the warning with a comment:
@Suppress("IMPLICIT_CAST_TO_ANY")
val chatObject = ...
Or explicitly state that the type that the if-else
expression returns is unknown:
val chatObject: Any = ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With