I have a java code like this:
String getData(Object obj)
{
if (obj instanceof String[])
{
String[] arr = (String[]) obj;
if (arr.length > 0)
{
return arr[0];
}
}
return null;
}
How should I convert this code into Kotlin? I have tried automatic Java to Kotlin conversion, and this was the result:
fun getData(obj:Any):String {
if (obj is Array<String>)
{
val arr = obj as Array<String>
if (arr.size > 0)
{
return arr[0]
}
}
return null
}
This is the error I've got from the kotlin compiler:
Can not check for instance of erased type: Array<String>
I thought that type erasure applies only for generic types, and not simple, strongly typed Java arrays. How should I properly check for component type of the passed array instance?
EDIT
This question differs from generic type checking questions, because Java arrays are not generic types, and usual Kotlin type checks using the is operator cause compile time error.
Thank you!
The correct way to handle this (as of Kotlin 1.2) is to use the isArrayOf
function:
fun getData(x: Any): String? {
if (x is Array<*> && x.isArrayOf<String>()) {
return x[0] as String
}
return null
}
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