13

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!

Michael P
  • 670
  • 7
  • 23
  • 1
    Possible duplicate of [How can I check for generic type in Kotlin](https://stackoverflow.com/questions/13154463/how-can-i-check-for-generic-type-in-kotlin) – Tim Jul 02 '18 at 13:06
  • 2
    This is not a duplicate, it's different because `String[]` is not a generic type in Java. – zsmb13 Jul 02 '18 at 13:11

1 Answers1

32

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
}
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
yole
  • 92,896
  • 20
  • 260
  • 197