简体   繁体   中英

Java to Kotlin converting problem | - or / & - and

I have some problems while converting Java code to Kotlin. This is example in java :

if ((deviceFd.revents & OsConstants.POLLOUT) != 0) {
    Log.d(TAG, "Write to device");
    writeToDevice(outputStream);
}

If we conver this code to Kotlin via Android Studio it produce something like this

if (deviceFd.revents and OsConstants.POLLOUT != 0) {
    Log.d(TAG, "Write to device")
    writeToDevice(outputStream)
}

But this code cannot be compiled because of error :

operator != cannot be applied to 'Short' and 'Int'

So what is the equivalent of Java code to Kotlin ?

In Java, & symbol is bitwise AND operator.

x & y

If two operands (x and y in this case) has different types. The value of the small type is promoted to the larger type implicitly.

byte, short, char => int => long

  • long & long => long
  • int & int => int
  • int & long => long & long => long
  • (byte|char|short) & int => int & int => int
  • (byte|char|short) & long => int & long => long & long => long

In your case

deviceFd.revents (short) & OsConstants.POLLOUT (int)

will be promoted

deviceFd.revents (int) & OsConstants.POLLOUT (int)

The result is int type.


In Kotlin, to do the same as Java.

Step 1. Because Kotlin DO NOT promotes the smaller type to the larger type implicitly, so you (as a programmer) must do it explicitly.

deviceFd.revents (short) => deviceFd.revents.toInt() (int)

Step 2. There is no & symbol in Kotlin, so you must use and to perform a bitwise AND operation between the two values.

deviceFd.revents.toInt() and OsConstants.POLLOUT

Put it together.

if ((deviceFd.revents.toInt() and OsConstants.POLLOUT) != 0) {
    Log.d(TAG, "Write to device")
    writeToDevice(outputStream)
}

Update: Based on the author's comment

deviceFd.events |= (short) OsConstants.POLLOUT;

Java

deviceFd.events (short) | OsConstants.POLLOUT (int)
deviceFd.events (int) | OsConstants.POLLOUT (int)
deviceFd.events = (short)(deviceFd.events (int) | OsConstants.POLLOUT (int))

Kotlin equivalent

deviceFd.events = (deviceFd.events.toInt() or OsConstants.POLLOUT).toShort()

Kotlin

deviceFd.events = deviceFd.events or OsConstants.POLLOUT.toShort()

Bitwise Operations is in experimental state, is there any better solution?

This is the only and official way to use Bitwise Operations in Kotlin. In addition, when compiling to Java bytecode, they still use Java Bitwise Operations ( | & ) under the hood.

By the way, Bitwise Operations is in experimental state, but when this feature is finalized, they will be moved to production state without breaking your current code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM