Introduction:

In today’s Internet age, new technologies are springing up like mushrooms after rain. Spirit brother also discussed with the development students what soft skills are indispensable to the growth of programmers? There was a lot of talk about the importance of exploring new technologies for programmers.

Spirit elder brother has a colleague who is keen to explore new technology — Benny (Huo Binggan). For those of you who follow Bugly regularly, you must be familiar with him. We have posted several articles written by Benny, such as “Understanding ButterKnife, Let your app Learn to code” and “Retrofit, such an awesome framework, why don’t you check it out?” , and so on…

Let’s find out what “Kotlin” is.

A, the past

There was a time when you were researching plugin development for Intellij and trying to compile the source code for Intellij Idea Community Edition (ICE), only to discover that there was a strange thing that prevented your code from compiling. What the hell? What the hell is KT?

There’s a new language. It’s crazy. At this point, the sentence pops into your head:

Have difficulties to go up, no difficulties to create difficulties to go up.

“Depend, this nima after all is who say of, good have reason!” You quipped.

You decided to learn Kotlin in order not to lose the good tradition of the new socialist youth, but seriously, this decision is also a trap for yourself, after all, Kotlin API is not stable at that time, often find a demo from the Internet, make up the local. By The time Kotlin 1.0 was released in February 2016, the messy API had calmed down with the once-restless heart, and you didn’t have to put up with anything, even the feeling of “finally watching your baby grow up”.

Getters and setters disappear

You’ve always loved Java, just like you’ve always loved your black coffee. And for the simple reason that you don’t know anything else. But there was a time when I was working on a voice chat app, in which the data structures of various users, call records and so on were so long that I could hardly see the edge of Getter and Setter. Every time I wrote a data structure class, it seemed that the golden rice fields were in front of me. When you blew a cup of coffee, they even made noise. The irony is that when you’re writing about Java, you’ll often find yourself writing something like this:

public class Person{ private int id; private String name; // Getters and setters are omitted. . }Copy the code

Well, such repetitive code takes up 80% of the space, so it’s no wonder that an IDE has features to help generate Getter and Setter templates.

You said you tried not to write getters and setters, but as someone who wrote Java for so many years, losing getters and setters makes you feel like…

At the time you looked at the properties in C# and wondered, “why can’t Java have this feature?”

Later, you discover that Kotlin actually has attributes:

data class Person(val id: Int, val name: String)Copy the code

You light up, put down your coffee and fantasize about a trip to Kotlin island sometime.

Third, see null pointer again

Your projects are all connected to Bugly, it’s like dancing on eggs and getting nervous to open crash statistics every day. The majority of these crashes are null pointer exceptions, which is not to say that there is something wrong with the null pointer itself, the null pointer can only indicate that the program has not considered the situation, the occurrence of the null pointer call is usually a code writing problem, so why Java will allow the existence of potential null pointer? You look out the window and wonder what must have blinded you to see, to see, to see.

Person.setname (" person.setName ");Copy the code

Come back to god, suddenly see this line of code, you mutter, this brother’s name is Orange right Jing, but this brother is who? What if it’s null?

Person person = findPersonFromCacheOrCreate(); Person.setname (" person.setName ");Copy the code

You look up at the assignment line, and you start to wonder, and you start to ask yourself, “Afraid not… we didn’t realize all this time that our Java code was giving us so much trouble.”

Coincidentally, one of the most common things you’ve seen recently while combing through project code is:

if(x ! = null) x.y();Copy the code

You are full of distrust of your code, what does your code reward you?

“Virtual machine empty pointer family bucket to a!… that must be very delicious” you a face of helpless self-mockery.

You suddenly realize that the code looks a lot like the world outside the window, but what brand of purifier should the code use?

“Mi’s afraid is not line.” You laugh and seem happy about it.

The joy is fleeting, and you have to face the agonizing reality. In Java in addition to you say to yourself “I promise findPersonFromCacheOrCreate () will not return empty”, are there any more steadfast approach? Of course not.

“Let’s see if Kotlin has a good idea!” So you try something like this with Kotlin:

fun findPersonFromCacheOrCreate(): String{
  ...
}Copy the code

When you attempt to return NULL in this method, the clever IntelliJ immediately draws a red line on your code telling you not to.

You look it up and discover that in Kotlin, String represents a non-null String type. This is the moment when you feel truly secure inside:

Val person = findPersonFromCacheOrCreate () person. Name = "orange right Beijing"Copy the code

People write findPersonFromCacheOrCreate this method must give you promise to return to the person is not null, he will be careful when writing this method, otherwise, the compiler will cut him.

“Cut my jacket! You suddenly think of micro letter inside that peach a northeast expression, think about good joy.

“But,” you think, “what if it returns NULL anyway?” Saying that you changed the code as Kotlin requested:

fun findPersonFromCacheOrCreate(): String?{
  ...
}Copy the code

It turns out that the second line below contains an error.

“What’s the matter?” You don’t understand.

Val person = findPersonFromCacheOrCreate () person. Name = "orange right Beijing"Copy the code

Only safe (? .). or non-null asserted (!! .). calls are allowed on a nullable receiver of type String?

“That is, if someone dare to return me a nullable type, I have to do short processing to be ok?” Your eyes light up and you exclaim, “That’s amazing!”

Next thing you know, the nullable type is returned, but that doesn’t stop you from having fun with your code, because Kotlin can give you a thousand options to make your code look like it’s flowing. If you want to return null, you can write:

val person = findPersonFromCacheOrCreate()? :returnCopy the code

Or if you can’t use a return here, you can still make sure your logic is executed when person is not empty:

val person = findPersonFromCacheOrCreate() person? .let{// use it to refer to person, never null} person? .setName(" Angela ")// executed only if person is not emptyCopy the code

Fourth, Smart Cast

“I heard that the wind has arrived in Zhangjiakou.” Arthur said. “Oh, well, we’ll really have to see.” You say calmly. “Wait for what, in front of a bright, ha ha.” Also happy. “Yeah, but right now I’d prefer Java to be smarter.” “What’s wrong with it?” “You see, Java has a particularly artless way of writing:

if(view instanceof ViewGroup){
  ((ViewGroup) view).addView(child);
}Copy the code

Strong method call, two pairs of parentheses, hand cramp. I’ve already told Java that the View is a ViewGroup, and it still feels like I’m on the subway and I swipe my card to get in, and when I get on the train, there’s still someone checking my ticket!” Say that finish, you suddenly feel thirsty, casually pick up hot coffee to drink a mouthful, you frown, that taste seems not very good.

“Although we write code should try to avoid strong turn, but you know this thing we can’t avoid, so was hoping to polymorphism in the parent class or interface by examples, the results much knowledge transfer code written to pervert. After if I judge the type of view, in this type of judgment within the scope of effective turn without stronger.” “You go on, looking worried.

“Kotlin can. Kotlin has a feature called smart-cast. You can write code like this:

If (view is ViewGroup){view.addView(child) // Now Kotlin knows that the view is ViewGroup. }Copy the code

Good, isn’t it?” Arthur had a look on his face.

‘Really! You say excitedly.

“You didn’t know that?” “Jokingly, as always, a real person playing a game on the side, who seemed even more pleased with himself than Arthur.

Five, log

“You connect log all dozen, true shameless..rightness, log is who, dozen time call top me!” You got that smirk on your face.

So, you have a function that takes three arguments,

void check(ArrayList<String> list, String tag, int id);Copy the code

You want to print out their values, so without thinking, you type a line of code:

System.out.println("list: "+list.size()+"; tag="+tag+"; id="+id);Copy the code

It doesn’t cause you any discomfort — after all, you’re used to it being ugly. You pause, wiggle your fingers, and suddenly think of that timeless joke:

Goddess: If you can make this forum noisy, I’ll go with you tonight. Programmer: PHP is the best language! Forum fryer, all kinds of quarrel. Goddess: Come on, let’s go. You can do whatever you want. Not today. I have to convince them that PHP is the best language.

“No wonder PHP is the best language out there!” You quipped, “At least they support string templates.”

$size = count($list);
echo "list: $size; tag=$tag; id=$id";Copy the code

I wonder if Kotlin has such a good feature. This guy has surprised you so much lately that you decide to give it a try.

println("list: ${list.size}; tag=$tag; id=$id")Copy the code

“HMMM ————” you nodded with satisfaction.

Goodbye, Utils

Not only have you used String before, but you also know that String doesn’t even provide an empty method. It’s ugly to write str.equals(” “) every time. That’s good. What if you happen to want to know that it’s not empty? This should be more common, so you write! Str.equals (” “) = = (” “); STR. Equals (” “))…

“How can you be so anti-human!!” You mutter and write a tool class in a fit of rage:

StringUtils.java

public class StringUtils{
  public static boolean notEmpty(String str){
    return !"".equals(str);
  }
   public static boolean isEmpty(String str){
     return "".equals(str);
  }
}Copy the code

You nod your head with satisfaction, feeling that you will never have to put up with ugliness again.

Then one day, the sun still tries to penetrate the haze to reach the front of your north facing house, but it doesn’t work, so you light a cigarette. And you are about to write a line called if(stringutils.notempty (STR)){… }, you quickly write if(STR. Tired eyes waiting for the IDE to catch your eye, but it is confused, String does not have a method called notEmpty. At this time you hesitated, slow god, flexible right little thumb from the keyboard; Go to backspace, delete STR. Write if(stringutils.notempty (STR)) again. What a distressing experience, you light a cigarette wistfully, and the air purifier in the room starts spinning.

“If I could rewrite the Java String class, I would add these methods first!!”

Then there was a flash of light, and these words were read across your window:

You almost cried out in surprise. “Is this really Kotlin?” You can’t believe your eyes. Yes, with extension methods, you don’t need XXXUtils anymore.

Good night, ButterKnife

“Good night.” You whisper to ButterKnife. You know this may be the last time you say it, because ButterKnife is starting to get a little overwhelmed in Kotlin’s world.

“You don’t need me anymore.” ButterKnife is tired. “No, you’re the best.” Sudden such a word, let you seem a little flustered. “Isn’t kotlin-Android-extensions enough?” ButterKnife became impatient. “But… but…” You’re at a loss for an answer, since you haven’t mentioned ButterKnife much since Kotlin came along.

Yes, you used to inject your views with a ButterKnife:

@BindView(R.id.nameView) TextView nameView; . Nameview.settext (" tangerine "); .Copy the code

And now? You shake your head, looking helpless. “No need to inject the View anymore?” You’re asking yourself how much you like your code now, despite all the bitterness of the past:

Nameview.text = "tangerine"Copy the code

No more ButterKnife, no more findViewById — it’s fate.

Please talk to my agent

Mr. SP is being sued for not persisting a new value after accepting it.

“Gentlemen, gentlemen, I can’t think of anything more important than my reputation. If you call commit when you update us, we will persist it as promised. Why don’t you commit?” Mr. SP was puzzled.

“Excuse me, Mr. SP, I am a reporter of Dalvik Daily. I would like to ask why we must commit?” “Hello, that’s the rule.” Mr. SP replied slowly. ‘But it’s a bit anti-human! “Asked the reporter. “It doesn’t matter, based on the lessons of the lawsuit, we specially hired Mr. Preference< T >, a high-tech talent, Mr. P is expert in this area.”

The reporter looked at Mr. P, trying to find something from him.

“Mr. P is a Delegate, and Mr. SP is Delegated Properties,” you say, walking out of the crowd.

“Yes,” Mr. P adjusted his glasses, “Sir, Mr. SP’s operation plan is a little complicated. Let’s take a look at an example:

context.getSharedPreferences("name", Context.MODE_PRIVATE)
  .edit().putString("key", "value").putInt("intKey", intValue).commit();Copy the code

When a gentleman needs to manipulate it, he must first get the SharedPreferences instance, then edit gets the Editor instance, and then save the value. On the one hand, the value saved is arbitrary, and the key value must be constrained, otherwise the reader will not be able to get the value. On the other hand, values can only be saved after commit. It’s really not very user-friendly.”

“What’s Mr. P’s opinion?” You’re curious.

“From now on, if you need persistent data from Mr. SP, you only need to register with me once. The rest of the data will take effect just like reading and writing variables.” Mr. P paused for a moment and looked around. Everyone was watching him, and Mr. SP also gave him a firm look.

“So in the future, if a gentleman needs us, for example, he needs to persist a data named ‘name’ with a value of ‘Orange Right king’, which of course can be changed, he just needs to do this:

Var name by Preference(context, "name", "sp_name")... Log.d(TAG, name) // The name of the TAG is the same as the name of the TAGCopy the code

We’ve really made reading and writing persistent data as straightforward as reading and writing variables in memory.”

“It was awesome.” You can’t help but applaud. “Mr. P, can I read your source code?”

Suddenly, your phone vibrates and interrupts your thoughts. You come back from meditation to find that you are still looking at your IDE, and that the code on the screen is Mr. P’s source code. It’s really clever:

You look reluctant to part. “SophisticatedPreferences aren’t exactly SharedPreferences, I think they must be mistaken, but help is more like SophisticatedPreferences. Mr P is simply sophisticated.”

Nine, a strong man to xi why no longer return?

You’ve thought long and hard about that. Is jing ke’s dagger not fast enough? Still not long enough?

“It’s not easy to use anyway.” You say in disgust.

There’s also a Dagger in Java called Dagger that generates some code for you.

“If code were smart enough to write code, wouldn’t we be out of a job?” I don’t know if you’re joking or just panicking.

Kotlin wasn’t able to use the blade before, which may have really discouraged a lot of people. However, this is no longer a problem, as you already knew kapt existed when you read the Kotlin 1.0.4 update. Just add the Apply plugin: With the “Kotlin-kapt” configuration, you can use a Dagger just like you do in Java — you even gave a demo a try. Programmers can’t shake the feeling of joy they get when they write a Hello World program successfully.

“There seems to be nothing wrong with Kotlin except that frameworks like FindBugs, which are tightly tied to Java syntax, can’t be applied directly to Kotlin.” You seem to be on to something.

Java and Kotlin dialogue

“Uncle Java, I… I’m afraid…” Kotlin says timidly. “My uncle is here.” Java patted her chest. “The world is yours, also is our, but at the end of the day is yours. You young vigor and vitality, are thriving period, like the sun at eight at nine o ‘clock in the morning. Hope on you. Baby, let go to do it, do not, for uncle, although uncle is old, but uncle still confident can fix it for you.”

You suddenly come to your senses, “I have such a big imagination, hahaha.”

Java and Kotlin dialogue 2

“Uncle Java, I… I’m afraid…” Kotlin says timidly. “My uncle is here.” Java patted her chest. “The world is yours, also is our, but at the end of the day is yours. You young vigor and vitality, are thriving period, like the sun at eight at nine o ‘clock in the morning. Hope on you. Baby, let go to do it, do not, for uncle, although uncle is old, but uncle still confident can fix it for you.” “All right, uncle, I’ll do it!” Kotlin’s cheeky grin really looks like a child. “I go, incredibly pack pitiful cheat your uncle, see I don’t hit you!” Java sputtered.

“It’s over, the imagination won’t shut up. You are intoxicated with the truth.

To you, Kotlin doesn’t seem like a new programming language. It looks more like Java syntactic sugar, only more thoroughly.

You take a sip of coffee, but this time it’s different. You put sugar in it.

If you want to learn more about Kotlin, check out this tutorial: Kotlin from Getting Started to quitting

Tutorial address: https://github.com/enbandari/Kotlin-Tutorials

(Click to read the original interview.)

If you think our content is good, please scan the QR code to appreciate the author and share with your friends


This article is the exclusive content of Tencent Bugly. Please mark the author and source prominently at the beginning of the article “Tencent Bugly(http://bugly.qq.com)”.