Code Xiaosheng, a technology platform focused on the Android field

Join my Android technology group

Author: industry loose links: https://www.jianshu.com/p/5961116ddba6 disclaimer: this article has been published, it has been approved industry loose forward etc. Please contact the author

Before talking about kotlin

There is a class of programmers who read a few sensationalistic blog posts about things they have never experienced, and I call them cloud programmers. Kotlin, for example, was criticized for writing a few “Why did I go back from Kotlin to Java” blog posts. Why not check out the Android Developer official website where all the sample code is kotlin version first and Java version last?

There is no point in arguing about the merits of language or framework. A lot of programmers talk up the languages and frameworks they use all the time and belittling other languages and frameworks. This is obviously a narrow programmer. Java is no. 1 all year round, but what about other languages? Of course not. Even to be critical, you have to have experienced it yourself. This is not a copy of what you did before, because learning a new language is a breeze for a real programmer.

Concise syntax

Kotlin strikes me as addressing all of Java’s pain points, such as cumbersome syntax, annoying null Pointers, and lack of functional programming support (Java8 supports Lambda expressions but doesn’t go far enough). Unlike its unrestrained twin, Scala, Kotlin struck me as smart and restrained, and a half day is enough for Java programmers to get started, unlike Scala’s high bar.

The Java language is one of the most syntactically cumbersome languages I’ve ever worked with (let me know if it’s more cumbersome), as evidenced by the main function, and it’s probably the only language where it’s almost impossible to use an IDE. Other languages can barely be written without IDE syntax warnings and code generation templates. Haven’t you tried Java code?

But the rigor and complexity of Java’s syntax is exactly why Java is so popular. Those of you who haven’t written Java may not understand this. People were not satisfied with Java’s strict syntax, but with check-style, Findbugs, and various XXX company Java code specifications, the end result was that all Java programmers wrote code that was mutually intelligible. Even a recent Graduate Java programmer who is familiar with Java object-oriented syntax will almost certainly be unable to read other Java code (except business). This ensures that Java programmers have a very high code floor, which ensures the success of large projects.

There’s been too much talk about Java. When you get to Kotlin, you can see that Kotlin has drastically simplified Java code while keeping as much syntactic rigor as possible as Java, and it’s very enjoyable to write.

// Create a Bean class data class Person(val id: Long, var name: String, var age: Int fun main() {val Zhangsan = Person(0L, "zhangsan", Age = 24 val name = zhangsan.name val lisi = zhangsan.copy(id = 1, Name = "lisi") // Tostring and equals/hashcode methods generated by default, Zhangsan.tostring () zhangsan.hashCode() var isEqual = zhangsan.equals(lisi)}Copy the code

Concise syntax is everywhere; the Bean class above, for example, would have been at least several times more coded in Java. Singletons simply replace class with object. These can be generated in seconds using various template generation tools in Java ides, but kotlin is more comfortable to write.

I want to emphasize that Kotlin is not mindlessly trying to simplify the syntax with syntactic sugar and new keywords, and it’s clear that Kotlin is trying to make the design process as syntactically rigorous as possible.

Null pointer

Java’s null-pointer exception is called a “Billion Dollar Mistake.” In order to avoid nullpointer exceptions at my previous company, the code specification required that almost all objects should be nullated. Json objects that are deeply nested can be very smelly and long to nullate.

val name: String? // Why does Kotlin not have a ternary operator? Name = if(random.nextBoolean ()) "Ann" else null Len1: len1: len1: len1: len1: len1: len1: len1: len1: len1: len1 val len1 = name? .length// Len2 = name? Val len2 = name? .length? Val len3 = name!! .lengthCopy the code

The above code explains three ways to handle potentially empty objects. In fact, I would classify Kotlin’s handling of null Pointers as adding a stereotype — a symbol — to all objects. Okay? , for belt? Object indicates that it may be null, so if you don’t handle it directly, you don’t allow compilation, which means that null Pointers are killed as much as possible during compilation. The idea is simple and clever. Many people hear Kotlin say there are no null Pointers, but they don’t know how to implement them if they haven’t used them. Now the interviewer asks you again, know how to answer?

Functional programming

fun AppCompatActivity.setupActionBar(@IdRes toolbarId: Int, action: ActionBar.() -> Unit) { val toolbar = findViewById<Toolbar>(toolbarId) setSupportActionBar(toolbar) supportActionBar? .run {// Executes the function in the argument, So the user when calling this method more flexible action ()} toolbar. SetNavigationOnClickListener {the d (" AppCompatActivity ", "finish") finish() }} / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- line -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / similar single method interface now only need to write a closure for the binding. AliPayIcon. SetOnClickListener {the d (" example, "it. ContentDescription. ToString ())} / / extension function, only when the object is not null will call, Let {it.setlifecycleOwner (this@WithdrawActivity) it.viewModel = vm}// Extend the apply function to call the method properties of the object directly within the closure. Apply {this.value = "aaaa" log. d("example", This.value?.toString() + ":" + this.hashcode ())}// There are other basic extension functions like run, with, also, etc. https://www.jianshu.com/p/28ce69d58feaCopy the code

Functional programming is new to many Java programmers. I don’t want to be a hack, but Java is so strong that many Java programmers only know Java and have virtually no exposure to Java8 or beyond. I don’t know any language that doesn’t support functional programming, except Java (below Java8).

Almost all languages support functional programming, so it’s really important to be flexible with it. Java is not supported because functional programming is relatively difficult, and not supporting it makes Java code lower bound. Aside from being a bit more difficult, one of the most frustrating things about functional programming is that it’s not very readable (depending on the level of the person writing the code). I can read the Java framework source code pretty well, but the JavaScript framework is pretty confusing. The Kotlin functional code is hard to read at my current level, but Kotlin is a strongly typed language, and it is not hard to read if the arguments and return types of functions are fixed.

Anyway, the benefit of functional programming is that you can double the flexibility of your code, and you can write all kinds of fancy code, which is obviously a double-edged sword. But as functional programming becomes more popular and people become better at it, the writing of functional code is bound to get better and better.

Arguably, the only difficulty for Java programmers learning Kotlin is functional programming, although this is not a problem if you already have functional programming experience. If not, you need to learn to understand functional programming, which is a relatively long process. Until you get comfortable with it, you can write Kotlin without using functional programming.

conclusion

My opinion of Kotlin is generally positive. But some people are not wired properly, so I would like to say that Kotlin is good, has advantages, and immediately someone screams that Java is going to be replaced. A couple of days later someone yelled at Kotlin and said he was going to get cold. I’m sure you understand the benefits and scope of Java. And the language that still uses a lot now has its own advantages, this I don’t Lao, after all the level is not enough. I’m sick of some bloggers and public accounts that rub heat and post soft articles to deceive themselves.

Don’t let me or Google tell you it’s good, and don’t let the China bloggers tell you it’s bad. When you have the time, why not take half an hour and try Kotlin?

I’m serious about sharing technology