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

时间:2019-03-17 19:56:48

标签: java android kotlin

在将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'

那么Java代码与Kotlin等效吗?

1 个答案:

答案 0 :(得分:3)

在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在两个值之间执行按位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()
  

按位运算处于实验状态,有没有更好的方法   解决方案?

这是在Kotlin中使用按位运算的唯一官方方法。另外,什么时候 编译为Java字节码后,他们仍然使用Java逐位操作(| &)。

顺便说一下,按位运算处于实验状态,但是当此功能完成时,它们将被移动 进入生产状态而不会破坏您的当前代码。