How can I check for array type (not generic type) in Kotlin

Michael P :

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!

yole :

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
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=441066&siteId=1