preface

Several features for quick start Kotlin

Fully understand Kotlin, fast writing business

Quickly switch to Kotlin for Android mode

Let’s talk about coroutines in Kotlin. Nice

The Kotlin article has been in the works for a long time. I never knew how to write it. Document writing? Why don’t you just read the document? Why don’t you need me to beep more? After some thought, I decided to write a quick post about getting a feel for Kotlin in Android development.

Honestly, I said no to Kotlin at first. Why? There is no real sense that replacing Java development with it has changed anything at all; And feel the grammar is very “awkward”! To put it bluntly, I don’t want to learn and find excuses for myself. Ha ha)

But then, serendipitously, Kotlin found something interesting. The beginning of all this, of course, is to overcome the “awkwardness” of writing Java for a long time (given that Lambda isn’t written much either). OK, cut it out. The article will begin with the “awkward” part of my encounter with Kotlin.

The body of the

A static method

The first one that stuck with me was static methods. It’s called in Kotlin: companion object. There is no “fancy” introduction. Directly on the code:

public class StringUtils{
	public static void myFun(a){
		Log.d("StringUtils"."Haha"); }}Copy the code

How does Kotlin write a static method in such a simple Java utility class?

class StringUtils{
    companion object {
        fun myFun(a){
            Log.d("StringUtils"."Haha")}}}Copy the code

Anonymous inner class

SetOnClickListener is a common use scenario for anonymous inner classes:

btn.setOnClickListener(new View.OnClickListener() {
	@Override
	public void onClick(View v) {
		Log.d("Listener"."Haha")}}Copy the code

So what does it look like in Kotlin?

btn.setOnClickListener {
	Log.d("Listener"."Haha")}Copy the code

It directly helps us Lambda. What would it look like if we didn’t want to Lambda?

btn.setOnClickListener(object : View.OnClickListener{
	override fun onClick(v: View?). {
		Log.d("Listener"."Haha")}})Copy the code

It’s nothing special. It’s just Kotlin’s syntax. Because variables declared in Kotlin are written first, their types are separated by: (:) and written after. That’s what it looks like right now. Note, however, that object represents the anonymous object type.

There’s a little detail here that I don’t know if the big brothers noticed. In Java, when we new an anonymous inner class: new View.onClickListener (){}, there is a (). In Kotlin: view.onClickListener {} has no (). This is also a syntax detail, plus () to indicate the constructor that calls this class.

Kotlin in RxJava

Let’s start with a very simple Java usage:

Observable.just(0)
          .map(new Function<Integer, String>() {
              @Override
              public String apply(Integer integer) throws Exception {
                  return integer.toString();
              }
          })
          .subscribe(new Consumer<String>() {
              @Override
              public void accept(String s) throws Exception {
	              Log.d("RxJava", s); }},new Consumer<Throwable>() {
              @Override
              public void accept(Throwable throwable) throws Exception {
	              Log.d("RxJava", throwable.getMessage()); }});Copy the code

For Kotlin, writing becomes unusually succinct with Lambda (and of course Java is succinct with Lambda) :

Observable.just(0) .map({ it!! .toString() }) .subscribe({ t: String -> Log.d("RxJava", t)
          }, { t: Throwable -> Log.d("RxJava", t.message) })
Copy the code

If Lambda is not very familiar with the big brothers, must be confused. So let’s switch to regular Kotlin. Does that sound familiar? Object is back, and yes, it’s just a normal anonymous inner class.

Observable.just(0)
          .map(object : Function<Int, String> {
              override fun apply(t: Int): String {
                  return t.toString()
              }
          })
          .subscribe(object : Consumer<String> {
              override fun accept(t: String) {
                  Log.d("RxJava", t)
              }
          }, object : Consumer<Throwable> {
              override fun accept(t: Throwable) {
                  Log.d("RxJava", t.message)
              }
          })
Copy the code

Kotlin in Adapter

Above several pieces of code, we feel together Kotlin in RxJava transformation. To be honest, if you throw a Lambda, it’s really not that much of a change. It’s a grammatical shift. Having talked about our daily development of RxJava, let’s take a look at another important Adapter. Here’s the Kotlin code:

class TestAdapter(var data: List<String>,var context:Context) : RecyclerView.Adapter<TestAdapter.ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup? , viewType:Int): ViewHolder {
        return ViewHolder(TextView(context))
    }

    override fun getItemCount(a): Int {
        return data.size
    }

    override fun onBindViewHolder(holder: ViewHolder? , position:Int){ holder!! .textView.text ="Haha"
    }

    class ViewHolder(var textView: TextView) : RecyclerView.ViewHolder(textView)
}
Copy the code

When I first looked at the code, I was a little confused and felt overwhelmed. In fact, Kotlin’s syntax is very easy to understand. When we first declare this class, we directly declare two var variables in the main constructor of TestAdapter. This is similar to Java:

class TestAdapter {
    public List<String> data;
    public Context context;

    public TestAdapter(List<String> data, Context context) {
        this.data = data;
        this.context = context; }}Copy the code

That’s why we can call data and context in class at will.

Note that var is a local variable if we declare it without var in the constructor. Applies only to constructors.

There shouldn’t be much to say about override’s code, so let’s look at the class ViewHolder declared last. Normally our ViewHolder in Java would look like this:

public class ViewHolder extends RecyclerView.ViewHolder {
    public TextView textView;

    public ViewHolder(TextView textView) {
        super(textView);
        this.textView= textView; }}Copy the code

Then why Kotlin, become a short line class ViewHolder(var textView: textView) : recyclerViewholder (textView)? In fact, there is no magic, just normal grammar. At the beginning of the summary, we mentioned the main constructor, and in the summary of the anonymous inner class, we mentioned the constructor that calls the class with the addition of () to indicate the display. So Kotlin’s code is easy to understand:

The end of the

OK, so that’s all about Kotlin’s awkward aspects of our Android development. To put it bluntly, these are basic grammar questions. The Android scenarios highlighted here are the ones I find awkward when I think I’ve learned the syntax. Of course, it is awkward because I do not understand the grammar. That’s why I wrote this article, hoping to give some help to those who are preparing to go Kotlin’s way

I am a fresh graduate, recently and friends maintain a public account, the content is that we in the transition from fresh graduate to the development of this way stepped on the pit, as well as our step by step learning records, if interested in friends can pay attention to it, together with fuel ~