Why use Kotlin? It’s completely compatible with Java, it’s not a problem to reference each other, so there’s no burden. I have been using Kotlin for nearly a month, and almost finished reading the grammar before I started the formal project. During this period, I was ready to give up for several times, but finally I persevered. There is no need to say more about Kotlin’s merits. Based on this month’s experience, let’s talk about Kotlin’s entry and pit.

The configuration of engineering

Add the dependent

As an Android coder, using Kotlin is easy. First, install the Kotlin plugin in Android Studio and search for Kotlin in Browse Repositories, the one with the most installs. After the installation is complete, press the Shift key 4 times, enter Config kotlin to search, select Config kotlin in Project, Android Gradle, app Module, and the Project configuration is complete.

Convert Java to Kotlin

To automatically Convert Java to Kotlin, press the Shift key 4 times and enter Convert Java Files to search

An introduction to

Variable declarations

  • Var variable
  • Val immutable variable

Declare the format of a variable

var str: StringCopy the code

Kotlin does not allow you to declare variables without initializing them. In the case of String, there are three ways to initialize them

Assign a non-empty value

var str: String = ""Copy the code

Set to null

var str: String? = nullCopy the code

Force null

var str: String = null!!!!!Copy the code

Kotlin is null-safe, but the third is an exception if a variable is assigned null!! , then declare that the variable is not null safe, even if used this way

var str:String = null!!!!! str.lengthCopy the code

The compiler also does not report errors

First, you can’t set STR to null or any other String after assignment, okay? The second way is to check every time you use it. If you use it directly, the compiler will report an error. This ensures null safety. Here’s an example:

var str: String = ""
// STR is not empty and can be used without checking whether it is empty
// You can optionally assign a non-null value to STR
str = "hello kotlin"

// The compiler will report an error
str = null

// If null is forced, STR is no longer null-safe and the compiler will not check STR
str = null!!!!!// declare str2 as nullable. Str2 is also null-safe
var str2: String? = null

// Using the str2 compiler directly will report an error
str2.length
// It can be used like thisstr2? .let { log(str2) }// str2 assigned to STR also returns an errorCopy the code

The end result is that using an empty variable will result in an error. Using a variable that may be empty will also result in an error. If checking for empty is too troublesome, Kotlin supports this

if(result? .data? .item? .name ! = null) {
    log(result? .data? .item? .name)}Copy the code

lamda

The magic of it

Kotlin’s lamda expression is concise, setting OnClickListener

textView.setOnClickListener {
    view -> openActivity(view.context)
}Copy the code

When only one parameter can be hidden, use it

textView.setOnClickListener {
    openActivity(it.context)
}Copy the code

Multiple parameters

checkbox.setOnCheckedChangeListener { compoundButton, b ->
}Copy the code

Kotlin’s function can be used as an argument, so we can write callback without interface

// Declare a callback
var callback: (()->Unit)? = null
// Judge and usecallback? .invoke()// Want to take parameters
var callback: ((str: String)->Unit)? = null
// Judge and usecallback? .invoke(str)// set callback
item.callback = {
    // do something
}
// Callback with arguments
item.callback = {
    doSomething(it)
}Copy the code

In the pit of

Databinding

You need to add it to build. Gradle in app moudle

kapt {
    generateStubs = true
}
dependencies {
    kapt 'com. Android. Databinding: the compiler: 2.2.0 - rc2'
}Copy the code

2.2.0 – rc2 the version number and must be under the root directory of the build. Gradle file within the com. Android. View the build: gradle: 2.2.0 – rc2 version number

Dagger2

The official blog says that Dagger2 is supported, but the actual situation is that it has problems with Databinding

Strange error

With Databinding, when you set up your ViewModel

cannot access class '... '.check your module classpath for missing or conflicting dependenciesCopy the code

Suppress(“MISSING_DEPENDENCY_CLASS”) @suppress (“MISSING_DEPENDENCY_CLASS”)

I can’t find the class when compiling. I need to clean it

Don’t know how to code

Java code prompt is very convenient, setListener, basically just type new, press enter to automatically complete the code prompt, how to write anonymous function

 textView.setOnClickListener(object: View.OnClickListener {
            override fun onClick(v: View?) {}})Copy the code

How do I write a static variable

class A {
    companion object {
        val TAG = "classA"}}// Used in Java code
A.Companion.getTAG()Copy the code

How do I convert from Kotlin to Java

The two methods

  • Package, output APK, use dex2JAR to extract APK code file into JAR, use JD-JUI to view, copy out the corresponding code, modify, and use
  • Delete the Kotlin file and rewrite it in Java
Tags: Android, Java
Good writing is the best
Pay attention to my
Collect the paper

sw926



Attention – 1



Fans – 24

+ add attention

5
0

The «The last:
Preview of new Android Studio 2.2 features



» Next up:
Use Designtime Layout Attributes in Android Studio