As a person who doesn’t stay up late at night, waking up to Kotlin as the official language of Android was a huge joy. In order to strike while the iron is hot, I decided to Release the article scheduled for this Sunday three days early. I hope to introduce you to Kotlin in time.

I’m sure many developers, especially Android developers, have heard of Kotlin at some point, but it doesn’t matter if they haven’t or aren’t familiar with it. This post and the rest of the blog will have a lot to share about Kotlin.

More than a month before writing this article, The Flipboard China Android project officially adopted Kotlin as the project’s development language, which means that new code files will appear in Kotlin code format and old Java code will be translated into Kotlin code. During the period of using Kotlin, I was shocked by its concise, efficient and fast features, so it is necessary to write an article to talk about the characteristics of Kotlin, and I would be glad if I can achieve the effect of promoting Kotlin.

Kotlin’s “Resume”

  • From JetBrains(Czech Republic, Eastern Europe), the famous IDE IntelliJ IDEA(Android Studio based on this) software development company
  • Originated from the St. Petersburg team of JetBrains and named after a small Island near St. Petersburg (Kotlin Island)
  • A jVM-based statically typed programming language

From well-known tool developer JetBrains, Kotlin’s DNA is bound to be functional and efficient. Let’s take a look at the characteristics of Kotlin, which is why I switched to Kotlin.

The syntax is simple and not verbose

Var currentVersionCode = 1 var currentVersionCode = 1 var currentVersionCode = 1 Var APPNAME = "droidyue.com" // Methods fun main(args: Array) { println(args) } // class class MainActivity : Appactivity () {} // data class automatically generate getters, setting, hashcode and equals methods data class Book(var name: compatactivity () {} // data class automatically generate getters, setting, hashcode and equals methods data class Book(var name: String, val price: Float, var author: String) // Support default parameter values, reduce method overload fun Context.showtoast (message: String, duration:Int = Toast.LENGTH_LONG) { Toast.makeText(this, message, duration).show() }Copy the code
  • Kotlin supports type inference without Java’s verbose.
  • In addition withvarRepresents variables,valConstants are much more compact
  • The method is simple: even function is shortened to fun to add a bit of a pun.
  • Class inheritance and implementation is simple, using:
  • Kotlin doesn’t need a semicolon (;) in every sentence.

Null pointer safety

Null Pointers (NullPointerException or NPE) are the most common crashes we see in Java development programs. Because in Java we have to write a lot of defensive code like this

public void test(String string) { if (string ! = null) { char[] chars = string.toCharArray(); if (chars.length > 10) { System.out.println(((Character)chars[10]).hashCode()); }}}Copy the code

In Kotlin the hollow pointer exception is well resolved.

  • Processing on a type, that is, following the type with? , that is, the variable or parameter and its return value can be NULL. Otherwise, assigning or returning NULL to a variable parameter is not allowed
  • For a variable or parameter that may be null, before calling an object method or property, add? Otherwise, the compilation fails.

The following code is an example of Kotlin’s implementation of null-pointer safety, and it’s a one-line implementation compared to a Java implementation.

fun testNullSafeOperator(string: String?) { System.out.println(string? .toCharArray()? .getOrNull(10)? .hashCode()) } testNullSafeOperator(null) testNullSafeOperator("12345678901") testNullSafeOperator("123") //result null 49 nullCopy the code

For the principles of null-pointer security, see this article to study some of Kotlin’s methods

Support method extension

A lot of times, apis provided by the Framework tend to compare atoms and require us to combine them when called, because it generates Util classes. A simple example is that we want to display Toast information more quickly, and in Java we can do that.

public static void longToast(Context context, String message) {
    Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}

Copy the code

But Kotlin’s implementation is amazing. We just need to rewrite the extension method. For example, the longToast method extends to all Context objects.

fun Context.longToast(message: String) {
    Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
applicationContext.longToast("hello world")
Copy the code

Note: Kotlin’s method extensions do not actually modify the corresponding class files, but rather deal with them on the compiler and IDE side. Makes it look like we’re extending the method.

Lambda, higher-order functions, Streams API, functional programming support

Lambda expressions are anonymous functions, which makes our code much simpler. For example, the following code is an application of lambda.

findViewById(R.id.content).setOnClickListener {
    Log.d("MainActivity", "$it was clicked")
}

Copy the code

The higher-order function is the function

  • You can accept functions as arguments
  • You can also return a function as a result

Take an example that accepts a function as an argument. In Android development, we often use SharedPreference to store data, and data changes cannot be applied if you forget to call Apply or COMMIT. We can solve this problem better by using the higher-order functions in Kotlin

fun SharedPreferences.editor(f: (SharedPreferences.editor) -> Unit) {val Editor = edit() f(Editor) editor.apply() PreferenceManager.getDefaultSharedPreferences(this).editor { it.putBoolean("installed", true) }Copy the code

Of course, in the above example we also use methods to extend this feature.

Kotlin supports Streams APIS and method references to make functional programming easier. For example, the following code combines Jsoup to capture the data of a proxy website, which is simpler and faster to implement.

fun parse(url: String): Unit {
    Jsoup.parse(URL(url), PARSE_URL_TIMEOUT).getElementsByClass("table table-sm")
        .first().children()
        .filter { "tbody".equals(it.tagName().toLowerCase()) }
        .flatMap(Element::children).forEach {
            trElement ->
            ProxyItem().apply {
                trElement.children().forEachIndexed { index, element ->
                    when (index) {
                        0 -> {
                            host = element.text().split(":")[0]
                            port = element.text().split(":")[1].toInt()
                        }
                        1 -> protocol = element.text()
                        5 -> country = element.text()
                    }
                }
            }.let(::println)
        }
}

Copy the code

String template

In both Java and Android development, we use string concatenation for logging and so on. In Kotlin, string templates are supported, making it easy to compose an array of strings

Val book = book ("Thinking In Java", "Unknown") val extraValue = "extra" log.d ("MainActivity", "book.name = ${book.name}; book.price=${book.price}; extraValue=$extraValue")Copy the code

Note: For more information on string concatenation, see this article for Java details: String concatenation

Good interaction with Java

Both Kotlin and Java are JVM-based programming languages. The interaction between Kotlin and Java is seamless. In this performance

  • Kotlin is free to reference Java code and vice versa.
  • Kotlin can use all existing Java frameworks and libraries
  • Java files can be easily converted to Kotlin with the help of IntelliJ plug-ins

Kotlin is widely used

Kotlin has extensive support for Android application development, with many tools such as KotterKnife (ButterKnife Kotlin version), RxKotlin,Anko, etc., as well as many existing Java libraries available.

In addition, Kotlin can also compile to Javascript. Recently, Kotlin wrote a section of code to grab proxy, which is very fast. It’s even faster than pure JavaScript.

fun handle(): Unit { window.onload = { document.getElementsByClassName("table table-sm").asList().first() .children.asList().filter { "TBODY".equals(it.tagName.toUpperCase()) } .flatMap { it.children.asList() }.forEach { var proxyItem = ProxyItem() it.children.asList().forEachIndexed { index, element -> when (index) { 0 -> { proxyItem.host = element.trimedTextContent()? .split(":")? .get(0) ? : "" proxyItem.port = element.trimedTextContent()? .split(":")? .get(1)? .trim()? .toInt() ? : -1 } 1 -> proxyItem.protocol = element.trimedTextContent() ? : "" 5 -> proxyItem.country = element.trimedTextContent() ? : "" } }.run { console.info("proxyItem $proxyItem") } } } }Copy the code

On performance

Kotlin’s execution efficiency is theoretically consistent with that of Java code. Sometimes Kotlin can be higher, for example, Kotlin provides inline Settings for methods, which can be set to inline for certain high-frequency methods, reducing the overhead of running in and out of the stack and saving state.

If you want to try Kotlin, its concise syntax, collection of features, high efficiency implementation, etc., has been popular in foreign countries, Pintereset, Square, Flipboard and other companies have started to use it in production.

About switching to Kotlin

In fact, before I made my decision (before Kotlin was officially appointed), I wondered if choosing Kotlin meant giving up Java. On second thought, it wasn’t really the case, because Kotlin’s syntax was too close to Java. And working with Java-related stuff all the time in Kotlin, so that’s not an issue.

For personal projects, it is usually not a difficult choice to turn to Kotlin. After all, Kotlin is such an excellent language that many people are willing to try and use this language with less effort.

The more difficult choice is how to make the team switch to Kotlin. I think there are many reasons why the team is difficult to switch to Kotlin, such as learning cost, historical burden and so on. But in fact, the root cause is the problem of way of thinking. People like to use tools to improve development efficiency, because of the high cost of manpower. Domestic teams are often more efficient by adding members. Fortunately, Flipboard’s US team has had Kotlin on board since 2015 (and probably before), so it makes it easier for the Chinese team to use Kotlin. Of course, the most important thing is that the current team size is small, and all members agree on Kotlin’s merits.

When it comes to teams switching to Kotlin’s approach, it usually makes sense to push it from the top down. This means that either the direct technical lead is open-minded or someone needs to keep pitching to influence the team.

To put this in perspective, Java is like a normal train from my hometown baoding to the west of Beijing that takes nearly 2 hours or more. Kotlin is the high-speed train that takes 40 minutes to get there. Ordinary people will choose high-speed rail because it saves time and improves the experience. This time and experience corresponds to programming that I think is highly efficient and highly readable and maintainable code.

Now, with Google’s support, Kotlin’s switch to Android will be fully rolled out in the near future. Tampering with Python’s famous phrase “Life is short, I use Kotlin”, a highly effective language that should be adopted by more and more teams into production. Of course, they also hope to shine in the domestic environment.