Home > database >  How to solve error with spread operator in kotlin?
How to solve error with spread operator in kotlin?

Time:05-06

I'm a Kotlin developer but I'm working on a java project, but when converting the classes through the sdk, this error appears. How to solve?

fun deviceIsConnected(): Boolean {
    var connected = false
    val myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
    if (myBluetoothAdapter != null && myBluetoothAdapter.isEnabled) {
        if (configsAndModels!!.strMACPROBE != null && configsAndModels.strMACPROBE != "") {
            val myDevice = myBluetoothAdapter.getRemoteDevice(
                configsAndModels.strMACPROBE
            )
           try {
                val m = myDevice.javaClass.getMethod("isConnected", null as Array<Class<*>>?)) //ERROR ON THIS LINE
               connected =  m.invoke(myDevice, *null as Array<Any?>?) as Boolean //ERROR ON THIS LINE
            } catch (e: Exception) {
                throw IllegalStateException(e)
            }
        }
    }
    return connected
}

JAVA :

 public boolean deviceIsConnected() {

    boolean connected = false;
    BluetoothAdapter myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (myBluetoothAdapter != null && myBluetoothAdapter.isEnabled()) {
        if (configsAndModels.getStrMACPROBE() != null && !configsAndModels.getStrMACPROBE().equals("")) {
            BluetoothDevice myDevice = myBluetoothAdapter.getRemoteDevice(configsAndModels.getStrMACPROBE());

            try {
                Method m = myDevice.getClass().getMethod("isConnected", (Class[]) null);
                connected = (boolean) m.invoke(myDevice, (Object[]) null);
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }
    }
    return connected;
}

CodePudding user response:

Your Java code is explicitly passing a null array as the varargs, which is unnecessary. You could simplify your Java code to the following, which implicitly passes an empty array:

Method m = myDevice.getClass().getMethod("isConnected");
connected = (boolean) m.invoke(myDevice);

Likewise, in Kotlin, you can omit the varargs if you're passing zero values:

val m = myDevice.javaClass.getMethod("isConnected")
connected = m.invoke(myDevice) as Boolean

Java allows the null array for backward compatibility (to versions that used arrays instead of varargs) and because it doesn't have null safety. Since Kotlin doesn't need the backward compatibility, it doesn't need to support null arrays.

  • Related