Pit encountered in Kotlin learning

Kotlin development is a trend of future Android development, and many companies have begun to use Kotlin to refactor their projects. In my spare time, I learned Kotlin by myself, and I also encountered many pitfalls in the use of kotlin, so I briefly summarized it, and I will make up for the problems in the future.

1. Create the pit encountered by the first pure kotlin project:

1.1 In the last step of creating a Kotlin project, select Add no Activity and click Create successfully.

1.2 In response to this situation, there are two places that need to be changed: gradle configuration and AndroidMainfest, I made an error in these two places, and the errors reported are "Error.Execution failed for task':app:processDebugResources'.>"

1.3 Solution

A. Add in the gradle configuration of the project

buildscript {
    ext.kotlin_version = "1.0.4"
    repositories {
        ...
    }
    dependencies {
        ...
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
     ...

B. Add in the gradle configuration of the Module

...
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
    ...
    defaultConfig {
        ...
    }
    buildTypes {
        ...
    }
}

dependencies {
    ...
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
}

C. Add the startup page to AndroidMainfest, otherwise it will not work.

<application ...>
        <activity ...>
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
</application>

2. Two pits encountered in Kotlin refactoring:

2.1 Kotlin code is executed from top to bottom. When writing Java code, we are accustomed to writing the adapters of member variables in the back. After the Java code is converted to Kotlin, an error will be reported. When the previous code calls the adapter of the following Kotlin code, because the adapter is behind, according to the smooth execution of Kotlin from top to bottom, the adapter is null at this time, and when running will report an error. So the adapter's data should be placed in front of the Kotlin code (outside the method in the class).

2.2 Kotlin method parameter with nullable type '? '. The parameters of the Kotlin code method may be empty, remember to add '? ', otherwise it will crash directly when the parameter is empty.

3 Java to Kotlin code:

When converting Java code to Kotlin code, you can quickly convert Java to Kotlin by using the shortcut keys Shift+Ctrl+Alt+K, or select Code->Convert Java File to Kotlin File.

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326995250&siteId=291194637