Kotlin 语法

[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...
}

你可能感兴趣的:(Kotlin 语法)