[TOC]
Java | Kotlin |
---|---|
A.class | A::class.java |
public常量:
Java
寫法如下:
public static final int STATE_IDLE = 0x0000;
Kotlin
寫法如下:
companion object {
@JvmField
val STATE_IDLE = 0x0000
}
private常量:
Java
寫法如下:
private static final String ACTION_USB_PERMISSION =
"com.android.cts.verifier.usb.device.USB_PERMISSION";
Kotlin
寫法如下:
private val ACTION_USB_PERMISSION = "com.android.cts.verifier.usb.device.USB_PERMISSION"
GetSystemService
Java
寫法如下:
UsbManager mUsbManager;
// way1
mUsbManager= getSystemService(UsbManager.class);
// way2
mUsbManager = ((UsbManager) context.getSystemService(Context.USB_SERVICE));
Kotlin
寫法如下:
// way1: added in API Level 23
mUsbManager = getSystemService(UsbManager::class.java)
// way2
mUsbManager = getSystemService(Context.USB_SERVICE) as UsbManager
單實例
val isDebug = SettingsHelper.getInstance().isDfuDebugEnabled
編譯錯誤如下:
Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type SettingsHelper?
正確寫法:
val isDebug = SettingsHelper.getInstance()!!.isDfuDebugEnabled
val size = Integer.parseInt((newValue as String?)!!)
Java
寫法如下:
while ((line = reader.readLine()) != null) {
if (line.contains("BtSnoopFileName=")) {
ZLogger.v( "line: " + line);
sb.append(line)
}
}
Kotlin
寫法如下:
Assignments are not expressions, and only expressions are allowed in this context
do {
line = reader.readLine()
if (line != null) {
ZLogger.v( "line: " + line);
sb.append(line)
}
} while (true)
kotlin 'return' is not allowed here
void test() {
if (a == null) {
return;
}
// TODO...
}
在kotlin里面可以寫成
fun test() {
a ?: return
// TODO...
}