The last part, Kotlin on how to solve Java development pain points, was written long by the programmer Happier, but he thought in the age of fast learning, few people would see it to the end. Did not expect, read the whole dig friends are not a few.

@lazy Yang jun encourage uncle, ask uncle to write another article, write more pain points, said that will come to uncle like, hope not to cheat uncle ~ ha ~

Today’s post is longer than the last one. Will you read the whole one? Ha ha ha ~ ~

Why did Google choose Kotlin?

Let’s start with some interesting gossip: Why did Google choose Kotlin over Java?

Did Google really choose Kotlin because it was better than Java?

“Kotlin is better than Java,” you can say for sure. That’s certainly not why Google chose Kotlin.

With Google’s research and development strength, it is fully capable to participate in the development of Java, so that Java becomes more and more easy to use. Even better than Kotlin.

From 2011 to 2014, Java was delayed for three consecutive years, and from 2014 to 2017, it was delayed for another three years.

After that, it resumed the rhythm of release [1 year and 2 versions]. Subsequent updates have certainly made Java easier to use.

Some even say that Java is starting to look like Kotlin.

What we discussed in the last post:

Kotlin string support, triple quotation marks “”” java14 also has this feature. [Java14 released in March this year]

Java7 also has the try-with-resources method to solve similar problems.

We will discuss this later:

Similar expressions are supported by when expressions, java14, and switch.

Smart conversions java14 is also starting to get smarter.

The point I want to make is that Java can get better and better. Google could have participated in iterations of Java, made it easier and easier to use, and even waited for Sun to borrow more of the language’s features. There’s no need to break all the bones and switch to Kotlin for Android as it would cost so many developers to switch languages. Not all developers love learning as much as their friends and uncles.

The most immediate reason for Google to choose Kotlin is because of the backlash against Sun.

In 2010, Sun sued Google for copyright and patent infringement by using Java code on Android.

History is strikingly similar. Sun has had success with Microsoft before. Hahaha…

13 years later, Sun is doing the same thing. Do you think Google is willing to do the same thing as Microsoft?

Let’s take a look at the Android official website, the Java tutorial about room:

All rights reserved. Java is a registered trademark of Oracle and/or its affiliates.

Google’s Java tutorial clearly states: All rights reserved. Java is owned by Oracle Corporation.

Google chose Kotlin just to get out of a patent lawsuit. Kotlin, of course, is also doing well. Really good performance.

Please eat a melon:

Google’s former CEO, Eric Schmidt, was a Sun executive, a very tall one.

Schmidt joined Sun in 1983, serving as chief technology officer and then chief executive.

The first vice president of engineering, Wayne. Wayne Rosen also worked at Sun.


Above, just uncle’s personal opinion, pure fantasy, no sun company and Google company’s actual information. Please keep thinking independently.

How does Kotlin solve the pain points of Java development [continued]?

Let’s move on to the second topic of the day. Moving on from one syntax feature to another, Kotlin addresses Java development pain points.

For those of you who didn’t read the last article on How Kotlin solved the Java development pain point and got the programmer Happier, you can read the last one first for more continuity.

2.1 Operators: == and ===

Let’s start with a Java question. When the uncle was a bright boy, he was tortured by the pain and happy, ha ha ~

Most Java veterans know this problem.

JavaEqualMain.java

public static void intEqual(a){
  Integer int127First = 127;
  Integer int127Second = 127;
  System.out.println("int127First == int127Second :" + (int127First == int127Second));

  Integer int128First = 128;
  Integer int128Second = 128;
  System.out.println("int128First == int128Second :" + (int128First == int128Second));

}
Copy the code


Uncle’s Soul Torture: What does the log output?

Uncle’s Soul Torture: What does the log output?

Uncle’s Soul Torture: What does the log output?


Does this look familiar? Did you meet him at the interview?

Did you pass the college exam? Ha ha ~

Log output:

int127First == int127Second :true
int128First == int128Second :false
Copy the code

Principle analysis:

public static void intEqual(a){
  Integer int127First = 127;
  Integer int127Second = 127;
  // Because the integers -128 to 127 are in the constant pool
  Int127First and int127Second point to the same object in the constant pool, so true
  System.out.println("int127First == int127Second :" + (int127First == int127Second));

  Integer int128First = 128;
  Integer int128Second = 128;
  Int128First and int128Second are different objects because 128 is not in the constant pool
  System.out.println("int128First == int128Second :" + (int128First == int128Second));

}
Copy the code

Let’s look at kotlin’s code again:

KtEqualMain.kt

fun intEqual(a) {
  val int127First = 127
  val int127Second = 127
  println("int127First == int127Second :" + (int127First == int127Second))

  val int128First = 128
  val int128Second = 128
  println("int128First == int128Second :" + (int128First == int128Second))

}
Copy the code


Uncle’s Soul Torture: What does the log output?

Uncle’s Soul Torture: What does the log output?

Uncle’s Soul Torture: What does the log output?


Log output:

int127First == int127Second :true
int128First == int128Second :true
Copy the code

That’s right, both of them are true.

According to?

Why is that?

Kotlin provides two equality operators == and ===

Equals () == : equals() ==

Reference Equality === : Determines whether two references refer to the same object

Uncle asks himself, what’s the use of the construct equality operator? What pain points can he solve?

Uncle asks himself, what’s the use of the construct equality operator? What pain points can he solve?

Uncle asks himself, what’s the use of the construct equality operator? What pain points can he solve?

There is a constant pool mechanism in the JVM. Strings and some wrapper objects may or may not have a constant pool.

A reference to the result of the equality operation, coupled to the constant pool, is true if both objects are in the constant pool, and false if one or both are not in the constant pool, even if the contents of the two objects are the same.

As a result, the reference equality operation, which is a little bit complicated, could get it wrong if you’re not careful.

The structure of kotlin is equal, regardless of the constant pool. The result of the equal method is not coupled to the constant pool. The result of the equal method is the same whether the object is in the constant pool or not.

It not only reduces the cost of learning for beginners. It also reduces the cost of making mistakes for older developers.

“===” kotlin’s “===” is the same as Java’s “==”, which should be familiar to those familiar with Python. Because python is like that, too.

And, and, and, in Kotlin, the structure equals equals equals is also going to help us automatically empty. Let’s look at the following two pieces of code.

The first is the Java code. JavaEqualMain.java

/** * Check whether the strings are equal */
public static boolean isTextEqual(String str1, String str2){
  if(str1 == str2){
    return true;
  }
  if(str1 ! =null&& str2 ! =null) {Str1 and str2 may either be null
    return str1.equals(str2);
  }
  return false;
}
Copy the code

Let’s look at kotlin, how do we do it: ktequalmain.kt

/** * Check whether the strings are equal */
fun isTextEqual(str1: String? , str2:String?).: Boolean {
  return str1 == str2
}
Copy the code

Yes, you read that right. Kotlin is that simple.

Kotlin’s isTextEqual() method is translated by the compiler as isTextEqual2() :

fun isTextEqual2(str1: String? , str2:String?).:Boolean{
    returnstr1? .equals(str2) ? : (str2 ===null)}Copy the code

The above section of code is explained in the official website documentation. www.kotlincn.net/docs/refere…


For those of you kotlin doesn’t know, you might be confused.

Uncle change him, and you’ll see.

fun isTextEqual3(str1: String? , str2:String?).:Boolean{
  if (str1 == null) {return str2 == null
  }
  return str1.equals(str2)
}
Copy the code

That’s why it’s automatically called empty.

To summarize:

Kotlin provides two equality operators == and ===

  • == == == == ==

    This is equivalent to calling object.equals () and handling the case where the Object is null.

  • === [Reference equality], whether the two references refer to the same object

    The Java equivalent of ==

Here’s another one of the usual interview questions

This question also is the question that interview often takes an examination of, we draw lessons from one example together ha.

Welcome, guys, let us know in the comments section:

Java code: javaequalMain.java

public static void stringEqual(a){
  String strBuilder1 = new StringBuilder("IT Internet Uncle").toString();
  String strBuilder2 = new StringBuilder("IT Internet Uncle").toString();
  System.out.println("strBuilder1 == strBuilder2 :" + (strBuilder1 == strBuilder2));


  String str1 = "IT Internet Uncle";
  String str2 = "IT Internet Uncle";
  System.out.println("str1 == str2 :" + (str1 == str2));
}
Copy the code

Uncle’s Soul Torture: What does the log output?

Kotlin code: ktequalmain.kt

fun stringEqual(a) {
  val strBuilder1 = StringBuilder("IT Internet Uncle").toString()
  val strBuilder2 = StringBuilder("IT Internet Uncle").toString()
  println("strBuilder1 == strBuilder2 :" + (strBuilder1 == strBuilder2))


  val str1 = "IT Internet Uncle"
  val str2 = "IT Internet Uncle"
  println("str1 == str2 :" + (str1 == str2))
}
Copy the code

Uncle’s Soul Torture: What does the log output?

2.2 Smart Casts

Let’s look at some Java code:

public static void close(Object obj) throws IOException {
  // Closeable is Closeable
  if(obj instanceofCloseable){ ((Closeable) obj).close(); }}Copy the code

Let’s look at Kotlin

@Throws(IOException::class)
fun close(obj: Any) {
  if (obj is Closeable) {
    obj.close()//obj is already Closeable}}Copy the code

We continue to

To continue

Above this writing method, Java code is not to see a little confused, do not understand, you busy on the right, uncle also confused.

Java’s strong shift to generics has seriously affected the readability of code.

Kotlin’s cast improves the readability of the code too much.

2.3 If and when expressions

val max =  if (a > b){
  print("a is bigger")
  a
} else if(a == b){
  print(" a == b")
  a
}else {
  print("b is bigger")
  b
}
//....
Copy the code

The above code can also be implemented using the when expression:

val max = when {
  a > b -> {
    print("a is bigger")
    a
  }
  a == b -> {
    print(" a == b")
    a
  }
  else -> {
    print("b is bigger")
    b
  }
}
Copy the code

Java’s ternary operator (condition? Then: otherwise), if expressions are more readable and more beginner friendly.

It is also more flexible than the ternary operator.

In addition, java14 switches are now expressions.

By the way, kotlin’s try and catch can also be used as an expression.

2.4 Destructuring Declarations

What is a deconstructive statement? What does deconstructing statements do?

2.4.1 Iterate over the Map by deconstructing the declaration

Let’s first look at how Java traverses a Map.

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("one".1);
map.put("two".2);

for (Map.Entry<String, Integer> entry : map.entrySet()) {
  System.out.println(entry.getKey() + "- >" + entry.getValue());
}
Copy the code

The above code is familiar to any Java programmer.

Not to brag, but since college, you’ve written more for loops than your kids have eaten salt.

It can be said that this way of Map traversal has been completely rooted in my mind. I think that’s what every program in the world should do.

Until one day, the uncle encountered Kotlin’s deconstructive statement:

val map = mapOf("one" to 1."tow" to 2)

for ((key, value) in map) {// Iterate over the Map by deconstructing the declaration
    println("$key->$value")}Copy the code

“Oh, my god, I can go through the Map like this.

That’s the way people think, guys.

This grammar is so sweet and concise. Basically, you don’t have to study. You know what it means at a glance.

When I first learned programming, I could learn C language in a week for loop traversal…

Next we find the source code for maps.kt:

Kotlin implements the component1() and Component2 () destruct declaration of map.entry class.

Next, let’s look at a code snippet:

fun main(a) {
  val people = People("IT Internet Uncle".18)
  var (myName, myAge) = people// Note this line of code to deconstruct the statement
  println("my name is $myName, i am $myAge")}class People(val name: String, val age: Int) {

  operator fun component1(a) = name / / note
  operator fun component2(a) = age  / / note
}
Copy the code

Because People overloads the functions component1() and Component2 (), it can be solved to form name and age.

Let’s see how Kotin did it.

Let’s look at his bytecode first.

What, bytecode? Uncle don’t tease me. What do you think?

Looks like trouble? It’s not easy to understand.

Well, the uncle couldn’t agree more.

So the uncle prepared another code fragment and decompiled the bytecode into Java code.

This syntax for deconstructing declarations, which is essentially syntactic sugar, has been optimized in the compiler.

It’s just that the compiler does us a favor by calling people.component1() and assigning it to us.

String myName = people.component1();
int myAge = people.component2();
Copy the code
3.4.2 Through the deconstruction declaration, the realization function returns multiple values

As we all know, Java functions can only have one return value. You cannot return more than one value at a time.

However, with the deconstruction declaration, we can pretend that the function can return multiple values, such as:

fun main(a) {
  val (myName, myAge) = getFirstPeople()// The return value is People. We can structure the return value directly
  println("my name is $myName, i am $myAge")}fun getFirstPeople(a) = People("IT Internet Uncle".18)
Copy the code

3.5. Unsigned integer

We know that Java doesn’t have unsigned integers, but Kotlin does. Hahaha.

UByte: unsigned 8-bit, ranging from 0 to 255 kotlin.UShort: unsigned 16-bit, ranging from 0 to 65535 kotlin.UInt: Unsigned 8-bit, ranging from 0 to 65535 Unsigned 32-bit bits ranging from 0 to 2^32-1 kotlin.ULong: Unsigned 64-bit bits ranging from 0 to 2^64-1Copy the code

Uncle’s self-interrogation: this can solve what pain point, labor has written Java for so many years, no unsigned plastic, is not still written well?

Uncle’s self-interrogation: this can solve what pain point, labor has written Java for so many years, no unsigned plastic, is not still written well?

Uncle’s self-interrogation: this can solve what pain point, labor has written Java for so many years, no unsigned plastic, is not still written well?

In the pain point 3.4 deconstruction statement we write a class People:

class People(val name: String, val age: Int) {}
Copy the code

Our age is an int. Int can be negative.

But is there a negative number for such a thing as age?

But is there a negative number for such a thing as age?

But is there a negative number for such a thing as age?

When we send the age in, do we need to do a data check?

If a colleague passed a negative number, resulting in a bug program, can only blame themselves not rigorous.

Similarly, to break your perception, does Java, divided by zero, necessarily crash? The bugs described in the blog.

So let’s change the code. Let’s say kotlin doesn’t have unsigned integers:

class People {
    private val name: String
    private val age: Int

    constructor(name: String, age: Int) {
        this.name = name
        if (age >= 0) {
            this.age = age
        } else {
            this.age = 0
            println("illegal age $age")}}}Copy the code

Since I have you, the world is so beautiful —— ˙

class People(val name: String, val age:UByte) {}
Copy the code

Not only more elegant but also more athletic.

Third, the end

All right, that’s technology. Uncle’s about to start talking.

Two days ago, there was a very senior old bird, older than the uncle, chatting with the uncle.

Veteran bird: “I made this demand, will be postponed.”

Uncle: “What’s wrong?”

Senior old bird: “this module, the previous implementation of a lot of use of LiveData, I have not used LiveData, and he is very complex, the code is hard to understand ah…”

Uncle: “er, how do you plan to do that?”

“I plan to rewrite this module, XXX colleague, this LiveData is too complex, a very simple logic, writing is very complex… I can’t change…”

Veteran bird: “ah, this team has not popularized the technology, it is best not to use it casually, and he used a very complex, a very simple function, around to around… I feel bad because of the tight project situation…”

Uncle: “……”

The uncle was really anxious for his colleague. I think he chose a very risky approach. In such an emergency, the risk of rewriting a module is often only higher.

What do you think, diggers? If you were an old bird, what would you choose?










Praise is a virtue. Give it a thumbs up and go, iron. 💖 Uncle needs your likes 👍