One, the introduction
A modern programming language that makes developers happier.
As the slogan of the website describes: kotlin is a modern language to make programmers happier when writing code.
And, as wikipedia says:
JetBrains hopes Kotlin will boost sales of IntelliJ IDEA
Kotlin is a language born for money, and I believe it will become a language with “money”.
JetBrains is a company that really treats programmers like people and users. From the pace of kotlin’s iteration and release, you can see that they’re iterating kotlin just like we programmers are iterating our company’s app, they’re valuing the user experience, they’re valuing the development experience of the programmers, and they’re improving the syntax that’s painful to write in Java. What Java programmers lack, they build for Kotlin. As a programmer, I mean, it’s really good.
Uncle, I have been developing Kotlin for more than two years. I can feel the happiness brought by Kotlin. Even, uncle sometimes has a sense of surprise when writing Kotlin. Let me have a feeling: Oh… You could still write code like this, you could still have this syntax.
After nearly a decade of writing Java code, He has become accustomed to accepting almost everything about Java, including some of the unpromising ways in which he takes for granted the way programming is supposed to be. Kotlin is subverting what the uncle is used to. Of course, this is not to belittleJava, Java is not only excellent but also great, Java iteration 24+ years, Java ecology is many languages can not match, it is the excellence of Java, Kotlin, Clojure, Groovy and a series of excellent languages. I’m sure someone here is going to jump in and say, PHP is the best language, let’s learn PHP
Uncle has a lot of friends around him. They are wondering whether to learn Kotlin or flutter.
On the one hand, they thought Java was enough. On the other hand, they thought That Google’s father had developed his son Flutter and that his son Kotlin was not the same blood after all. And the ability of flutter to cross multiple ends was greater than that of Kotlin, so it was concluded that there was no need to learn Kotlin.
However, kotlin is now used in many projects and companies, and it can be seen in official Google documents and demos. Start rocking again, tangled, confused, anxious. Uncle thinks kids make choices, and uncle learns what the company needs.
Let’s briefly clarify the essential differences between flutter and Kotlin.
The flutter and Kotlin positions are completely different, their principles are completely different.
The Flutter can simply be understood as a UI engine, and the cross-platform capability is something he was born with. It’s like a game engine.
Kotlin’s advantage is that he inherits all the capabilities of Java. And I’m expanding my capabilities. His ability is not limited to Android development, back end development, JS development. Even more, the uncle saw that Kotlin was trying to steal Python’s turf.
Kotlin and Flutter are not incompatible technologies. Even if the team chose to develop their app with Flutter on some modules, kotlin could still shine on the original android code.
Sounds like a lot of nonsense. Let’s get down to business.
How does Kotlin solve the pain points of Java development?
Let’s go through the syntax features one by one, starting with the most basic string
2.1 Kotlin string support, triple quotation marks “”” “
Let’s go straight to the code, javahtml.java
public class JavaHtml {
private static final String HTML =
"
\n" +
"<HTML>\n" +
"<head>\n" +
"<meta charset=\"utf-8\">\n" +
"IT Internet uncle \n" +
"</head>\n" +
"<body>\n" +
"
\n" +
"\ n"
\n" +
"</body>\n" +
"</HTML>";
}
Copy the code
If double quotation marks exist in the string, backslashes are used to escape them.
String concatenation is necessary if you want to wrap lines to improve readability;
The HTML code, which is easy to understand, becomes obscure.
Is this code for people to read? We’ve endured 24 years since the release of Java. None of them have improved.
Let’s look at the triple quotes of the Kotlin string. KotlinHtml.kt
val HTML = "" "
< HTML >
IT Internet uncle
"""
Copy the code
Grace? Happy?
2.2 Kotlin String templates
So let’s take a look at PeopleJava’s toString method. —– This toString method is automatically generated by AndroidStudio.
public class PeopleJava {
private String name;
private int age;
public PeopleJava(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString(a) {
return "PeopleJava{" +
"name='" + name + '\' ' +
", age=" + age +
'} '; }}Copy the code
Let’s take a look at PeopleKt’s toString method.
class PeopleKt (private var name:String, private var age:Int) {override fun toString(a): String {
return "PeopleKt{name='$name', age=$age}"}}Copy the code
Let’s write a main method using kotlin again, and see if we can log the two objects.
fun main(a) {
print(PeopleJava("IT Internet Uncle".18).toString())
println()
print(PeopleKt("IT Internet Uncle".18).toString())
}
Copy the code
Log output:
Before always hear people say concise beauty, concise beauty, concise how can be associated with the United States.
Now the uncle understands. Simplicity is not only beautiful, it is easier to understand simple things.
2.3 Kotlin supports default parameters
Default parameters are not unfamiliar to us, uncle learned the default parameters when learning C/C ++ in college. The concept is also very simple.
The following code:
class A {
fun foo(i: Int = 10) {
/ * * * * /}}Copy the code
The a.foo () method, if called with no arguments, defaults to 10 for argument I
Uncle’s self-interrogation:
Default arguments, what’s the use? What pain points in Android development can be addressed?
Default arguments, what’s the use? What pain points in Android development can be addressed?
Default arguments, what’s the use? What pain points in Android development can be addressed?
In Android development, when we write a custom View, we often have to write several constructors.
JavaTextView.java
public class JavaTextView extends AppCompatTextView {
public JavaTextView(Context context) {
super(context);
}
public JavaTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public JavaTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr); }}Copy the code
With the default parameters, after…
KotlinTextView.kt
class KotlinTextView : AppCompatTextView {
constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = android.R.attr.textViewStyle
) : super(context, attrs, defStyleAttr){
}
}
Copy the code
2.4 kotlin coroutines
Let’s go straight to the code. The following code comes from: Getting Started with Kotiln coroutines in one minute, thread switching
override fun onCreate(savedInstanceState: Bundle?). {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Context switch to the IO main thread
// Using global coroutines directly in an Activity may cause memory leaks. Do not imitate. Thank you @saifei for pointing out that the uncle did not notice this problem because of his convenience. Thanks again @Saifei for pointing out the problem.
GlobalScope.launch(Dispatchers.IO) {
Log.i(TG, "Dispatchers.IO isMainThread ${isMain()}")/ / output is false
// Context switch to the main thread
GlobalScope.launch(Dispatchers.Main){
Log.i(TG, "Dispatchers.Main isMainThread ${isMain()}")/ / output true}}}Copy the code
Previously we used to use Handler, AsyncTask and other classes to achieve thread switching.
But when you have coroutines. I feel a lot happier than WHEN I was writing Handler.
Switching threads is just the tip of the iceberg for coroutines, which are powerful and worth learning more about.
The kotlin use function automatically closes closeable
We implement a function in Java and kotlin that reads the first line of the file:
JavaFileUtil.java 】
KotlinFileUtil.kt
Clearly kotlin’s use is much more elegant than Java’s.
So let’s look at the implementation of the use function.
2.6 the findViewById ()
Java code:JavaFindViewActivity.java
Initially, a cast was required after each findViewById, as shown in this code
TextView tvTitle = (TextView) findViewById(R.id.tv_title);
Copy the code
Later, I don’t remember which version of androidstudio has been updated so I don’t need to do type hardening. The code looks a lot cleaner.
Then someone made a plugin called ButterKnife that didn’t have to call findViewById yourself. All you have to do is write some notes. I don’t think it’s very elegant. [Most Android veterans know this]
It wasn’t until I came across Kotlin’s Kotlin-Android-Extensions extension that I found elegant.
KotlinFindViewActivity.kt
There are no calls to the findViewById() method and no annotations.
Everything is so beautiful.
Third, the end
Wow ~~ uncle can write this in one breath… Long technical blog, you can see here, I think you are really patient.
I was going to write a few more pain points, but I looked at the length of it and I decided not to. Most people won’t see the end. I’ll just throw a brick
Thank you in this impetuous times, can calm down to see a middle-aged greasy uncle’s garrulous. Uncle wish you soar in kotlin’s world ~ hope kotlin can bring you happiness ~
How Kotlin solves Java development pain Points
Praise is a virtue. Give it a thumbs up and go, iron. 💖 Uncle needs your likes 👍