繁体   English   中英

Java到Kotlin转换问题| - 或/和 - 和

[英]Java to Kotlin converting problem | - or / & - and

将Java代码转换为Kotlin时遇到了一些问题。 这是java中的示例:

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

如果我们通过Android Studio将此代码转换为Kotlin,它会生成类似的内容

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

但是由于错误,无法编译此代码:

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

那么与Kotlin相当的Java代码是什么?

在Java中, 符号是按位AND运算符。

x&y

如果两个操作数(在这种情况下为x和y)具有不同的类型。 小类型的值被隐式提升为更大的类型。

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

在你的情况下

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

将被提升

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

结果是int类型。


在Kotlin中,与Java一样。

步骤1.因为Kotlin 不会隐式地将较小的类型提升为较大的类型,所以您(作为程序员)必须明确地执行它。

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

步骤2.Kotlin中没有符号,因此您必须使用在两个值之间执行按位AND运算。

deviceFd.revents.toInt() and OsConstants.POLLOUT

把它放在一起。

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

更新:根据作者的评论

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相当于

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

科特林

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

Bitwise Operations处于实验状态,有没有更好的解决方案?

这是在Kotlin中使用Bitwise Operations的唯一官方方式。 此外,在编译为Java字节码时,它们仍然使用Java Bitwise Operations( | & )。

顺便说一下,Bitwise Operations处于实验状态,但是当这个功能完成后,它们将被移动到生产状态而不会破坏您当前的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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