Technology little black room




  • Home page
  • Dry goods shop
  • The archive
  • Reading a book
  • about
  • cooperation
  • donation
  • To subscribe to
  • Best Gay friends
  • push
  • welfare
  • Friends of the chain

Why should I switch to Kotlin

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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//variables and constants
var currentVersionCode = 1   // The current version number of the variable. The type Int can be inferred from the value
var currentVersionName : String = "1.0" // Specify the type explicitly
val APPNAME = "droidyue.com" // Constant APPNAME type (String) can be inferred from the value

//methods
fun main(args: Array<String>) {
    println(args)
}

// class
class MainActivity : AppCompatActivity(a) {
  
}

// The data class automatically generates getters, setting, hashcode, and equals methods
data class Book(var name: String. val price: Float. var author: String)

// Support default parameter values to reduce method overloading
fun Context.showToast(message: String. duration:Int = Toast.LENGTH_LONG) {
    Toast.makeText(this. message. duration).show(a)
}
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


1
2
3
4
5
6
7
8
public void test(String string) {
    if (string ! = null) {
        char[] chars = string.toCharArray(a);
        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.


1
2
3
4
5
6
7
8
9
10
11
12
fun testNullSafeOperator(string: String?). {
    System.out.println(string? .toCharArray()? .getOrNull(10)? .hashCode())
}

testNullSafeOperator(null)
testNullSafeOperator("12345678901")
testNullSafeOperator("123")

//result
null
49
null
Copy 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.


1
2
3
public static void longToast(Context context. String message) {
    Toast.makeText(context. message. Toast.LENGTH_LONG).show(a);
}
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.


1
2
3
4
fun Context.longToast(message: String) {
    Toast.makeText(this. message. Toast.LENGTH_LONG).show(a)
}
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.


1
2
3
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


1
2
3
4
5
6
7
8
9
10
fun SharedPreferences.editor(f: (SharedPreferences.Editor) -> Unit) {
    val editor = edit(a)
    f(editor)
    editor.apply(a)
}

// The actual call
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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
fun parse(url: String) : Unit {
    Jsoup.parse(URL(url), PARSE_URL_TIMEOUT).getElementsByClass("table table-sm")
        .first().children(a)
        .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(a)
                        }
                        1 -> protocol = element.text(a)
                        5 -> country = element.text(a)
                    }
                }
            }.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


1
2
3
val book = Book("Thinking In Java". 59.0 f. "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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
fun handle() : Unit {
        window.onload = {
            document.getElementsByClassName("table table-sm").asList().first(a)
                    .children.asList().filter { "TBODY".equals(it.tagName.toUpperCase()) }
                    .flatMap { it.children.asList(a) }.forEach {
                var proxyItem = ProxyItem(a)
                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(a) ? : -1
                        }
                        1 -> proxyItem.protocol = element.trimedTextContent(a) ? : ""
                        5 -> proxyItem.country = element.trimedTextContent(a) ? : ""
                    }
                }.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.


My Zhihu Live recommendation

  • I learn the android stuff
  • How can a programmer write a good technical article?

What do you like?

  • Talk about dependency injection
  • My summary of 2016
  • The raspberry Pie guide to getting started
  • Select a list of quality articles
  • Six books programmers must Read
  • 9 Books Java Programmers must Read
  • Android signature related knowledge
  • An in-depth look at ArrayMap in Android
  • Static and dynamic binding in Java
  • Personal blog access speeds up a hundredfold solution
  • Shi Don’t three years, my latest personal work
  • Thinking about worker threads in Android
  • Note: When applying permissions for Android applications
  • Android WebView intercepts and replaces network request data

Posted by androidyue Kotlin

« A simple and practical Android debugging app tips


Recommended reading

Particularly recommended



The latest article

  • Why should I switch to Kotlin
  • A simple and practical Android debugging application tips
  • Study some of Kotlin’s methods
  • Some personal experience about speeding up Gradle builds
  • Error-prone,Google’s Java and Android Bug analysis tool
  • Control the width of RecyclerView Item
  • A simple and useful way to find performance problems in Android
  • Container expansion issues for Java performance tuning
  • A small improvement to android packaging speed
  • An in-depth look at ArrayMap in Android
  • Android application multi-process sorting
  • A Java reflection library with twice the effort
  • Why should programmers try blogging
  • My summary of 2016
  • Some analysis of object pooling

Blogrolls

  • Technology little black house shopping
  • Kindle commuter reader
  • XBrowser- Simple and fast browser
  • Digital Ocean VPS: $10 free for registration
  • Vultr VPS, $20 free for registration, abundant nodes
  • Github programmers, geeky IT men and women fall/winter hoodie jackets
  • NETGEAR WIFI Dual-band Gigabit Wireless Router Relay OPENWRT multi-dial

Good book recommendations

  • meter
  • see
  • Cut off from
  • The little prince
  • The dark time
  • At the top of the wave
  • Sakamoto ryoma did
  • The mystery of silicon valley
  • The beauty of mathematics
  • The collapse of China
  • Make wine and explore the west
  • Translation skills
  • 100 years of Silicon Valley
  • Ugly Chinese
  • Crazy Programmer
  • The Romans
  • Emperor: Liu Bowen
  • How to read a book
  • Think of time as a friend
  • Misunderstood Japanese
  • The rise and fall of the Third Reich
  • A Brief history of Man: From Animals to God
  • The Mob: A study of mass psychology
  • A minimalist History of Europe that you’d love to read
  • Revelation: Build products that users love
  • Wharton’s most popular success course
  • Out of control: The Ultimate Fate and end of all Mankind
  • History of The Chinese people, Mr. Bo Yang prison works
  • The three-Body Problem, Asia’s first Hugo Award winning work
  • This history is quite reliable: Yuan Tengfei speaks world history
  • Starting a business is Hard: How to do something Harder than Hard
  • Don’t let your future self hate your present self
  • Animal farms are not simply a political fairy tale
  • The origin of modern “Japanese studies” is chrysanthemum and dao
  • Man can be destroyed, but not defeated: Biography of Chu Shijian
  • Illustration of the Pomodoro Technique: A simple time management method
  • Give up! Procrastination: The Psychology of Procrastination for Young People
  • Geek physics: The most interesting questions and Surprising Answers on Earth

Programming a good book

  • algorithm
  • The code of
  • Code of the pulp
  • One month myth
  • The programming of mission
  • The beauty of the programming
  • Aha! algorithm
  • Hackers and Painters
  • Unix Programming art
  • The Definitive GUIDE to HTTP
  • Clean code
  • Programmer’s Cry
  • Interesting binary
  • The way of programmer training
  • Birdman’s Linux home dish
  • Yuhiro Matsumoto’s world of programming
  • Data structure and algorithm analysis
  • Deep understanding of computer systems
  • Gradle for Android
  • 45 Habits of Effective Programmers
  • How does a computer run
  • The construction and interpretation of computer programs
  • Refactoring: Improving the design of existing code
  • Agile Software Development (Principles, Patterns and Practices)
  • The foundation of reusable object-oriented software with design patterns
  • The Programmer’s Mind: Nine lessons for Developing Cognitive Potential
  • Coding: The language behind computer hardware and software (timeless computer science classic)

Java classic

  • Effective Java
  • Java Programming ideas
  • Java concurrent programming practice
  • Java Core Technology Volume I
  • Java Core Technology Volume ii
  • In-depth understanding of the Java virtual machine
  • The way of Java programmers
  • The definitive guide to Java Performance optimization
  • Java Virtual Machine Specification (Java SE Version 7)

Recommended Books for Android

  • Android wing preach
  • Deep Understanding of Android
  • Android development art exploration
  • Android application performance optimization
  • Android Game development in detail
  • Deep dive into Android security architecture
  • Gradle For Android
  • Android software security and reverse analysis
  • Android development progression: from geek to expert
  • Android source code design pattern analysis and combat

Popular articles

  • Talk about ANR in Android
  • Android scans multimedia files for analysis
  • The data area of the JVM runtime
  • Why should programmers try blogging
  • A simple and practical Android debugging application tips
  • ViewStub is used in Android to improve layout performance
  • Android WebView intercepts and replaces network request data
  • An Android code JIT friendliness detection tool
  • String constant pool in Java
  • How to detect the current thread as the main thread in Android
  • Note: When applying permissions for Android applications
  • 9 Books Java Programmers must Read
  • Funny Programmer Moments (Season 1)
  • Private modifier for “invalid”
  • Study some of Kotlin’s methods
  • Android code specification tool: Checkstyle
  • The Google Play store promotes those things
  • Programmer’s funny is the ultimate moment
  • Use Android Lint to find and fix older API issues
  • A small improvement to android packaging speed
  • A simple little tool, the Uploader for Octopress
  • Java detail: concatenation of strings
  • Are you kidding? The stopped state of an Android application
  • The most detailed article on Java and JavaScript interaction in Android
  • Where did Java permanent go

Check out droidyue_com


Copyright © 2017 – androidyue – Octopress Cloud Storage Provider: