Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 818
Michael P Avatar asked Jul 02 '18 13:07

Michael P


1 Answers

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
}
like image 199
yole Avatar answered Nov 10 '22 15:11

yole