Translate error in java to Kotlin


#1

Hello !

I am using the datasheet from android studio but it does not success to translate java to kotlin and I am not very strong in Java. this is the code :

HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Iterator deviceIterator = deviceList.values().iterator();
while(deviceIterator.hasNext()){
UsbDevice device = deviceIterator.next();

}

It seems that I succed to translate the first Line :
var deviceList = manager.getDeviceList()

But now, I am stuck…

Thanks for your help


#2

Your first line is valid. I would suggest changing the var to val instead as it is good practice to use val where ever possible (val is the equivalent to java final). For the rest

val deviceList = manager.getDeviceList()
val devecieIterator = deviceList.values.iterator()
while(deviceIterator.hasNext()){
    val device = deviceIterator.next()
}

This would be the direct translation. But I would still change a few things. If you don’t need a reference to the iterator for some other reason you could simplify this again by usinging

val deviceList = manager.getDeviceList()
for((key, device) in deviceList){ // see destructing declaration
    ...
}
// or
for(device in deviceList.values){
    ...
}
// or
deviceList.values.forEach { // see Higher order functions and lambdas
    ...
}

destructing declaration, higher order functions and lambdas


#3

it works ! thanks a lot !!