It seems I’m having a hard time getting rid of my talkative habit. Read on.

Can we talk about something else first?

Don’t talk about something else, the in the mind hold back to panic ah, don’t know how to start ah, I this person is to chat and chat more up, so the old brothers don’t panic, sit down to drink a cup of tea to listen to me slowly break off;

Host: “How old are you?”

Me: “This is somebody else’s secret (TMD where run a host come out? .”

Compere: “yo yo yo, embarrassed all come, understand ~ that you married yao? No, married?”

Me: “This is a big dating show? What about Kotlin’s introduction?”

Host embarrassed smile, the appearance of a pair of XXX (” months “) said: “I’m sorry, I’m sorry, but professional habit, professional habit”, then the no-nonsense said “that you simply introduce myself first your use of Kotlin, in addition, the presence of the bosses, can leave the base, after all it is not able to bear or endure look.”

Say something serious

Kotlin had been on the radar for 17 years, and by then a small group of people had taken a liking to Kotlin and were exporting it wildly in certain communities. I was fascinated by Kotlin at the time, because I started my career as a cross-platform developer (Android and iOS in C#, then called mono, now called Xamarin), so when I learned that Kotlin could be applied to Android, iOS, Web, and even Server, I started to try Kotlin out of curiosity at that time and suffering from the long-standing criticism of Java (tedious, callback purgatory, etc.) (I learned Java in college, I used C# for my graduation work, and I felt the advantages of C# language level).

As Kotlin got to know it, I fell in love with it. At that time, Kotlin was promising to be 100% interoperable with Java. I was so brave that I started to use Kotlin for actual application scenario development in some scenarios, and if I remember correctly, the version at that time was 1.0x. Google announced Kotlin as the recommended Development language for Android, and KT1.1 was released along with it. With the strong support from Google, I felt confident and fully embraced Kotlin. Since then, I have mainly used Kotlin for follow-up new business development and reconstruction.

Developers have a lot of fun talking about languages, and it would be nice to say “PHP is the best language” — no, “Kotlin is the best language for Android” — in a group. As a result, Kotlin may still be doubted by some. In fact, I also know that there is anxiety in everyone’s heart, too much anxiety, even about the future of the “Flutter” and “Aandroid” next door. Anxiety is always anxiety, however, why should we go to the outcome of the election today anxiety “sichuan and the founding of the” or “understand the king”, am I the bug will be a bit less, so anxious rather let yourself Happy, don’t every day his beleaguered, his own work well to cope with bad circumstances, to talk about “anxiety”, will be more and more “coke”, Finally they paste up and are reaped; Of course, we also need to consider the actual environment, some want to use but are restricted by conditions, such as the company does not use, such as the introduction of difficulties, concerns about the impact of existing projects and other problems; So to use it or not to use it, we need to be part of the larger community and think in terms of our environment. My advice is that if you’re working on Android and you’re not going to change that anytime soon, you can choose Kotlin on your project, don’t reject Kotlin;

For me, developing with Kotlin is happy, it improves my work efficiency and saves development time, which is definitely happy for a developer.

“Kotlin is just syntactic sugar, I don’t care”, “Kotlin is too bad”, “Kotlin increases compile time”, “Kotlin is too hard to learn”, “Kotlin coroutine is what the hell, RxJava smell?” “Language is only skill, internal skill is king”…

This is… Where do you want me to start? You are a mule or a horse. Don’t just listen to what others say. Truth comes from practice and chastity comes from practice.

Come on Kotlin, let’s find out who Kotlin really is.

Speaking of which, I have opened the study document on Kotlin’s official Chinese website.

The official learning resources are very good, which I think is the best and most complete way to learn Kotlin. Official document address here, young man, good cheer: read the official document, rely on the credibility of the son; Official document address.

After all, Kotlin is a complete language, and if you can explain it in a few words, it’s bullshit, and I’m just scratching the surface.

Hello, World

Classes, variables and methods are the three most common elements of a program, so we can get started with these three things first, and then improve the rest.

To avoid too much complexity, let’s take a look at a piece of code that is well-behaved, as compared to Java as possible;

Kt class Study1 {// define a class // define a String read-only variable val content: String = "Hello,World." // Define a private String variable. String = "SuperLuo" // define a variable of type protect protected var age:Int = 18 // constructor(name: Constructor (name:String,age:Int){this.name = name this.age = age} // Define a method fun sayHello() { Println (this.name + ": \"" + content + "\""); Funsum (a: Int, b: Int): funsum (a: Int, b: Int) Int {return a + b} private fun printCurrentDate(){println(Date().toString())}}Copy the code

Although the sparrow is small, the five organs are complete, the example is very simple, but also deliberately as far as possible in the form of Java to write, after all, we are familiar with Java.

Since Kotlin and Java are almost 100% interoperable, meaning they can call each other, this makes sense simply because both are JVM languages, and eventually both will compile into JVM supported class files. We’ll figure out what’s up there, and then we’ll figure out what we owe, step by step.

variable

Kotlin declares variables through val and var. The difference is that val cannot be changed after assignment, whereas var can.

Kotlin has a nice feature ->” type inference “; If the type of a variable can be inferred from its value, the type of the variable can be omitted:

Var x = 5 // automatically infer 'Int' type x += 1Copy the code

Of course, there are cases where Kotlin can’t infer the type correctly, so specify the type if you need to define it, val Content: String = “Hello,World.”;

In Kotlin, everything is an object; Basic types in Java have corresponding object types, such as Integer for int and long for long. So in Kotlin, there are no base types, only object types (where the Integer type is Int instead of Integer in Java, and so on). The official explanation for why this is done is not clear to me, and at first it was a little weird for me, but later I thought it was ok. Unification of rules is good for some things, especially with extension functions;

For example, many places in the program need to handle the display of the number of likes, when the number of likes is 0, it will be displayed as “like”, when the number of likes is greater than 10,000, it will be displayed as “x. xw”, then we can do as follows:

// Define an extension to handle the display rule inline val int.asFAVORString {return when(this){0->" like ">10000 ->" ${this.div(10000.0)}w" else -> this  } } fun apply(){ val textView:TextView .... Textview. text = 1. AsFavorString}Copy the code

Of course, the above example is not very appropriate, and more is the function of the extension function, but for a brief overview.

function

Kotlin uses the fun keyword to declare functions, as follows:

(Visible modifier, such as private, defaults to public) fun function name (argument list): return value {}

// Public method fun sum(a: Int, b: Int): Int {return a + b} // A private method with no arguments // This function returns Unit. Unit is a special object in Kotlin (and is implemented as a singleton). Private fun printCurrentDate():Unit{println(Date().tostring ())} Private fun printCurrentDate(){println(Date().toString())}Copy the code

class

The Kotlin class is also defined using the class keyword and the constructor is declared using constructor. In general, it’s not that different from Java.

use

Since Kotlin and Java can co-exist, that is, they can be developed in a hybrid way, so there will be calls to each other, and there will be slight differences in the way they call each other;

Java usage scenarios:

@test public void useStudyClassInJava() {// Create object Study1 instance = new Study1("SuperLuo"); Println ("content=" + instance.getContent()); system.out.println ("content=" + instance.getContent()); // Call the object function instance.sayHello(); Int result = instance.sum(1, 2); System.out.println("1+2=" + result); }Copy the code

Kotlin usage scenarios:

@test fun useStudyClassInKt(){// Create object val instance = Study1("SuperLuo") // print the content variable value Println ("content=${instance.content}") // call the object function instance.sayhello () // call the object function with parameters val result = instance.sum(1,2) println("1+2=$result") }Copy the code

The above code results (both results are identical) :

Content =Hello,World. SuperLuo says: "Hello,World." 1+2=3Copy the code

As can be seen from the above, there are only slight grammatical differences between the two, both in terms of definition and use, so there should be no obstacles in the above content.

Kotlin didn't use the 'new' keyword when creating the object, and Java code used the 'getContent()' method when accessing the object's content variable. I'll talk about why this is the case later. In addition, Kotlin's println function is actually a call to Java's System.out.println method. For String concatenation, Kotlin used the String template writing method, which is equivalent to the Effect of Java's String.format methodCopy the code

Abstract classes, interfaces

The previous has a simple understanding of classes, functions, variables, but also used, classes can be said to be very important components of the program, and classes are closely related to the other things are abstract classes and interfaces;

An abstract class

Abstract class Person {var name: String val age: Int // Abstract attributes: You can define abstract attributes and methods, whereas Java only has abstract methods. Abstract var sex: String constructor(name: String constructor) String) {this.name = name //age = 18} String fun printInfo() {println("${name} year ${age} year ${sex}, live in ${getAddress()}")}} String) : Person(name){override val sex: String get() = "male" override fun getAddress(): String {return "Mars"}}Copy the code

I won’t introduce it in detail, but I can simply look at the notes. We define an abstract class, and we define a subclass, so we write a scenario that uses these two classes;

@test fun testAbstract() {val me = Male(" Xiao Luo ") me.printinfo ()Copy the code

It’s not that different from Java, but we know that in Java development, we can create anonymous classes to quickly use abstract classes or interfaces, which we probably use a lot:

SetOnClickListener (new view.onClickListener (){@override public void onClick(View)  v) { } });Copy the code

So how do you create anonymous class objects in Kotlin? The above code is written in Kotlin as:

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

We use the previously defined Person class as an anonymous class:

@Test fun testAnonyClass(){ val she = object:Person("Siri"){ override val sex: String get() = "override fun getAddress(): String {return" sun "}} she.printinfo ()Copy the code

interface

In Java, we can think of an interface as a special kind of abstract class, that is, all the methods of the interface are abstract, but Kotlin is different. The interface in Kotlin can contain either the declaration of the abstract method or the implementation. But unlike abstract classes, interfaces cannot hold state.

// Interface Gun {// Damage: Fun printPower(){println(" $power")} // Define an abstract shooting method fun shoot()} class AK: Gun { override val power: Int = 100 override fun shoot() {println(" use AK ")}} @test fun testInterface() {val AK = AK() ak.printpower () Var waterGun = object: Gun {override val power: Int get() = 0 override fun printPower() {println() {override fun shoot() {println()} override fun shoot() {println()} } watergun.printpower () watergun.shoot ()Copy the code

The use of interfaces and abstract classes is similar;

Come to an end

To be honest, writing the basis is boring. Ha ha, so the end of the first hastily, temporarily here, calculate to understand, for a programming language grasp or suggest systematic learning, so I still hope to see the official documents for learning the best.

After talking about so many things in front of you, maybe some friends are wondering if Kotlin is the only one? So boring!

I would say no, if Kotlin were nothing more than that, there would be no reason for it to exist, otherwise it would just be a foreign language version of Java, but the opposite; The above code scenario is very simple. Secondly, I have deliberately made Kotlin’s code as easy to understand as possible, and as similar as possible to the way it is implemented in Java, so it is harder for us to feel Kotlin’s charm. Frankly, Kotlin’s “manipulation” has not started yet, for fear of making too many things different from the Java way. It’s gonna be hard for the cute ones to digest. Let’s take our time and experience Kotlin’s manipulation.

Later we mainly focus on the practical application of Kotlin and some “SAO” operations, to feel the charm of Kotlin, I will also use more actual scenarios to explain.

Andme making address

Welcome to group communication: QQ276097690

More welcome to pay attention to public number

If you have more suggestions or exchanges, welcome to join the group discussion, add the public account can be the first time to understand the latest content.