I have said this pit many times, why is there someone stepping on it? A deep pit that Kotlin may bring (last reminder)

Write in front

Last year, oh no, in May of the previous year, Google announced the important concept of Kotlin-First, claiming that Kotlin is the language of choice for Android developers.

After the news was sent out, many people had a question in their minds: Then I am engaged in Android development, can I just learn Kotlin in the future?

Generally, people who have this question or idea are laymen or people who have recently entered the industry.

Today, I will share the views of an industry leader. This article can also be used as a novice manual for mobile development. Hope this article is helpful to everyone.

From the public account: Chengxiang Ink Shadow

The content of this article:

  • Potential pitfalls that Kotlin may bring
  • analysis Summary
  • Mobile development learning

Potential pitfalls that Kotlin may bring

I. Introduction

The new language has new features, and developers still keep the Java programming habit to write Kotlin, which is not bad, but it always feels almost meaningless.

Recently, the official account "Google Developers" serialized a series of articles on "Building Android Applications with Kotlin | Kotlin Migration Guide", which exemplified some Kotlin coding tips.

Since it is a guideline article, it is natural to omit some details on the basis of "many and broad". At the same time, there may be some inappropriate places in the example scenes.

Here I will fill in these details, and today I will talk about the use of Kotlin's method default parameter characteristics to complete the effect of Java-like method overloading. Completely analyze the usage and principle of this feature, as well as a deep pit in the use process.

2. Kotlin's easy method overloading

2.1 How does Kotlin simplify method overloading?

In Java, we can define multiple methods with the same name in the same class. We only need to ensure that each method has a different parameter type or number of parameters. This is Java's method overloading .

class Hello {
    public static void hello() {
        System.out.println("Hello, world!");
    }

    public static void hello(String name) {
        System.out.println("Hello, "+ name +"!");
    }

    public static void hello(String name, int age) {
        if (age > 0) {
            System.out.println("Hello, "+ name + "(" +age +")!");
        } else {
            System.out.println("Hello, "+ name +"!");
        }
    }
}

In this example, we define three of the same name of hello()the method, having different logical detail.

In Kotlin, because it supports in the same method, the nullable parameters are marked by " ? ", and the default value of the parameter is given by " = ". Then these three methods can be softened into one method in Kotlin.

object HelloDemo{
    fun hello(name: String = "world", age: Int = 0) {
        if (age > 0) {
            System.out.println("Hello, ${name}(${age})!");
        } else {
            System.out.println("Hello, ${name}!");
        }
    }
}

Calling in the Kotlin class is consistent with the effect of the previous Java implementation.

HelloDemo.hello()
HelloDemo.hello("承香墨影")
HelloDemo.hello("承香墨影", 16)

But this method, which is declared by the characteristics of the default value of the Kotlin method parameter, is somewhat different when used in a Java class. Because HelloDemo class is declared object, so the need to use Java INSTANCEto call its methods.

HelloDemo.INSTANCE.hello("承香墨影",16);

Kotlin call the hello()method is very convenient, you can selectively ignore parameters, but using in Java, it must explicitly to do the whole amount parameter assignment.

This is how the method declaration using parameter default values ​​is used in Kotlin and Java respectively. Next, let's take a look at the principle.

2.2 The principle of specifying default values ​​for Kotlin method parameters

The code written in Kotlin can be run in the virtual machine of the Java system mainly because it will be compiled into Java bytecode that can be recognized by the virtual machine during the compilation process. So we can get the corresponding Java code generated by Kotlin through two conversions (Show Kotlin Bytecode + Decompile).

public final void hello(@NotNull String name, int age) {
  Intrinsics.checkParameterIsNotNull(name, "name");
  if (age > 0) {
     System.out.println("Hello, " + name + '(' + age + ")!");
  } else {
     System.out.println("Hello, " + name + '!');
  }
}

// $FF: synthetic method
public static void hello$default(HelloDemo var0, String var1, int var2, int var3, Object var4) {
  if ((var3 & 1) != 0) {
     var1 = "world";
  }

  if ((var3 & 2) != 0) {
     var2 = 0;
  }
  var0.hello(var1, var2);
}

Here you will generate a hello()method, while there will be a synthetic method (Synthetic Method) hello$default, to deal with default parameters. Kotlin call the hello()method, during compilation will, replaced with automatic selective hello()synthetic methods to call.

// Kotlin 调用
HelloDemo.hello()
HelloDemo.hello("承香墨影")
HelloDemo.hello("承香墨影", 16)

// 编译后的 Java 代码
HelloDemo.hello$default(HelloDemo.INSTANCE, (String)null, 0, 3, (Object)null);
HelloDemo.hello$default(HelloDemo.INSTANCE, "承香墨影", 0, 2, (Object)null);
HelloDemo.INSTANCE.hello("承香墨影", 16);

Note the example of the end, when hello(name,age)the time this method overloading, in fact, call in Java, is the same, it's really nothing.

This is the principle of using Kotlin method overloading to specify default parameters, eliminating the need for multiple method overloading codes.

After understanding the principle, I found that it does reduce the amount of code we write, but is there a scenario where we need to explicitly overload these methods? Naturally, such as when customizing the View.

3. Custom View meets Kotlin

3.1 The construction method is also a method

Going back to the aforementioned Google developer " Building Android Applications with Kotlin | Kotlin Migration Guide " series of articles, the examples given are actually very inappropriate.

In the example here, the word View is used, and several methods of overloading are all the construction methods of View. When we customize View, we often deal with these three methods.

But the examples given by Google engineers here are easy to misunderstand. In fact, if you write this way when customizing the View, you will definitely get an error.

For example, we customize a DemoView, which inherits from EditView.

class DemoView(
        context: Context, 
        attrs: AttributeSet? = null, 
        defStyleAttr: Int = 0
) : EditText(context, attrs, defStyleAttr) {
}

This custom DemoView, when used in the XML layout, although the compilation will not make an error, you will get a NoSuchMethodException when running.

Caused by: java.lang.NoSuchMethodException: <init> [class android.content.Context, interface android.util.AttributeSet]

What's the problem?

When LayoutInflater control is created, you can not find DemoView(Context, AttributeSet)the overloaded methods, so on the error.

This is actually very easy to understand. I mentioned the principle of Kotlin using methods with default values. In fact, Kotlin will eventually generate an additional one after compilation 合成方法to handle the default value of the method parameters, which is the same as Java's method overloading. It's not the same. The method generated by it does not have multiple method overloads.

So understand that Kotlin's method specifying default parameters is not equivalent to Java's method overloading . It can only be said that they have similar characteristics in certain scenarios.

3.2 Use @JvmOverloads

So back to the question here, in custom Views or other scenarios where Java method overloads need to be preserved, how can Kotlin actually generate corresponding overloaded methods when compiling?

Here we need to use @JvmOverloadsup.

When Kotlin used the default value of the method is increased @JvmOverloadsannotated after its meaning is compiled, maintained and overloaded methods to expose more of the method .

In fact, when we customize the View, AS has already given us sufficient hints, and it will automatically generate a @JvmOverloadsconstruction method for us.

The code that AS helped us complete is as follows:

class DemoView @JvmOverloads constructor(
        context: Context, 
        attrs: AttributeSet? = null, 
        defStyleAttr: Int = 0
) : AppCompatEditText(context, attrs, defStyleAttr) {
}

Then "Kotlin Bytecode + Decompile" look at the compiled code, to verify the @JvmOverloadsresults.

@JvmOverloads
public DemoView(@NotNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
  Intrinsics.checkParameterIsNotNull(context, "context");
  super(context, attrs, defStyleAttr);
}

// $FF: synthetic method
public DemoView(Context var1, AttributeSet var2, int var3, int var4, DefaultConstructorMarker var5) {
  if ((var4 & 2) != 0) {
     var2 = (AttributeSet)null;
  }

  if ((var4 & 4) != 0) {
     var3 = 0;
  }

  this(var1, var2, var3);
}

@JvmOverloads
public DemoView(@NotNull Context context, @Nullable AttributeSet attrs) {
  this(context, attrs, 0, 4, (DefaultConstructorMarker)null);
}

@JvmOverloads
public DemoView(@NotNull Context context) {
  this(context, (AttributeSet)null, 0, 6, (DefaultConstructorMarker)null);
}

As you can see, @JvmOverloadsafter it takes effect, the corresponding overload method will be generated according to our expectations, while the synthesis method is retained, and the requirement of using the default parameters when used in Kotlin is completed.

Do you think it's over here? No, if you completely follow the instructions given by AS to generate code when customizing the View, although the program will not crash, you will get some unknown errors.

3.3 Don't directly use AS to generate code in View

When customizing the View, relying on the AS prompt to generate code, you will encounter some unknown errors. For example, in the example of this article, we want to implement a subclass of EditView and generate code with AS prompt.

What will happen?

In the EditView scene, you will find that the focus is gone, and the soft keyboard will not automatically pop up after clicking.

Then why is there such a problem?

The reason lies in AS's handling of parameter default values ​​in the automatically generated code.

When customizing the View, when the overloaded method is generated through AS, its processing rules for the parameter default values ​​are like this.

  1. When encountering an object, the default value is null.

  2. When encountering a basic data type, the default value is the default value of the basic data type. For example, Int is 0 and Boolean is false.

In the scenario here, defStyleAttrthe type of this parameter is Int, so the default value will be assigned to 0, but it is not what we need.

In Android, when the View is used for layout through an XML file, it will call the two-parameter construction method (Context context, AttributeSet attrs), and it will call the three-parameter construction method inside and pass a default one defStyleAttr. Note that it is not 0.

Now that the problem is found, it is easy to solve. We take a look at the Custom View parent, how to achieve constructor two parameters will defStyleArrtwhen passed defaults into the like.

Then we look at AppCompatEditTextthe implementation.

public AppCompatEditText(Context context, 
                         AttributeSet attrs) {
    this(context, attrs, R.attr.editTextStyle);
}

Then modify the DemoView to defStyleAttrspecify them default.

class DemoView @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null, 
        defStyleAttr: Int = R.attr.editTextStyle
) : AppCompatEditText(context, attrs, defStyleAttr) {
}

So far, in the custom View, the problem of overloading the construction method using default parameters has also been solved.

In the Custom View scenes, of course, it can be rewritten more constructorto achieve a similar effect method, but since it has been to understand how it works, then go ahead and use it.

2. Summary moment

At this point, it is clear that in Kotlin, the use of default parameters to reduce the usage skills and principles of method overloading code, as well as precautions.

Understanding the principles and points to be noted can help us make better use of Kotlin's features. We finally summarize the knowledge points of this article:

  1. Kotlin can achieve the effect similar to "method overloading" in Java by specifying default values ​​for the parameters of a method.

  2. If you want to retain overloaded Java methods, you can use @JvmOverloadsannotation mark, it will automatically generate all overloads of the method.

  3. When Custom View, need to pay attention to the specified parameter defStyleAttrdefault values, and should not be zero.

Three, mobile development study guide

The above has analyzed a deep pit that Kotlin may bring, and I think everyone has an answer to the initial question in their minds.

Mobile development, especially Android development, is still dominated by the Java language (Java language is still the most versatile), and the main things that need to be learned for Android development are the following.

(1) The architect builds the foundation language foundation

At present, the mainstream language for Android APP development is the Java language. The biggest feature of the Java language is to increase the possibility of software interaction. It can be said that almost all applications on Android phones are written in the Java language.

Knowledge points:
1. In-depth understanding of Java generics
2. Explaining in-depth explanations
3. Concurrent programming
4. Data transmission and serialization
5. Principles of Java virtual machine
6. Efficient IO

image

(2) Interpretation of the open source framework by design thinking

With the continuous development of Internet companies, there are more and more modules in product projects, and user experience requirements are getting higher and higher. It is more and more difficult to achieve the purpose of small steps and fast iterations, and the application of plug-in technology is born. If there is no plug-in technology, the applications that integrate a large number of "app" such as Meituan and Taobao may be as big as a few g.

Therefore, today's Android mobile development will not be hot-fixed, plug-inized, or componentized, and more than 80% of the interviews will not pass.

Knowledge points:
1. Hot fix design
2. Plug-in framework design
3. Component framework design
4. Picture loading framework
5. Network access framework design
6. RXJava responsive programming framework design

image

(3) 360° all-round performance tuning

In the hands of development engineers at different levels, because of the uneven technical level, even if many mobile phones are running with very high software performance, there will still be lag when opening applications.

In addition, with the iteration of product content, the functions become more and more complex, and the UI pages become more and more abundant, which also becomes an obstacle to smooth operation. In summary, the performance optimization of APP has become a comprehensive quality that developers should have, and it is also a guarantee for developers to complete high-quality application works.

Knowledge points:
1. Design ideas and code quality optimization
2. Program performance optimization
Start-up speed and execution efficiency optimization
Layout detection and optimization
Memory optimization
Power consumption optimization
Network transmission and data storage optimization
APK size optimization

3. Development efficiency optimization
Distributed version control system Git
automated construction system Gradle

4. Project actual combat
Start-up speed and
fluency
The practice of Douyin's APK package size resource optimization practice
Full analysis of Youku responsive layout technology
Network optimization
Mobile Taobao Double Eleven performance optimization project Secret AutoNavi
APP full-link source code reliance analysis to
completely kill the actual combat of OOM Experience sharing
WeChat Android terminal memory optimization practice

image

(4) Android framework system architecture

Android framework architecture (advanced UI+FrameWork source code) This piece of knowledge is currently the most users, and we call it the technology of Android from 2013 to 2016.

Android developers are often familiar with and unfamiliar with this frequently "used" code because they are used to copying code on the Internet: the familiar is dealing with them almost every day and copying the code every day; the unfamiliar is that although with these codes every day Dealing with codes, but I haven't studied the principles of these codes in depth and the connotations in the depths of the codes.

Knowledge points:
1. Advanced UI promotion
2. Android kernel components
3. Essential IPC for large projects
4. Data persistence and serialization
5. Framework kernel analysis**

image

(5) NDK module development (audio and video development series)

NDK (abbreviation of Native Development Kit) is a software development kit based on a native programming interface that allows you to use C and C++ code in Android applications. The program developed by this tool runs directly locally, not a virtual machine.

In Android, NDK is a collection of a series of tools, mainly used to extend the Android SDK. NDK provides a series of tools to help developers quickly develop C or C++ dynamic libraries, and can automatically package so and Java applications into an apk.

Knowledge points:
1. Introduction to C/C++ developed by NDK
2. JNI module development
3. Linux programming
4. Low-level image processing
5. Audio and video development
6. Machine learning

image

(6) Advanced Flutter learning

2020 is undoubtedly a year in which Flutter technology is in full swing. Now this technology is still very valuable.

Every mobile developer is crazy about the features and concepts of "rapid development, expressive and flexible UI, native performance" brought by Flutter, from super apps to independent apps, from pure Flutter to hybrid stacks, developers We are enthusiastic about exploring and applying Flutter technology in different scenarios, and we are also facing a variety of different challenges.

Knowledge points:
1. Overview of Flutter cross-platform development
2. Building Flutter development environment in Windows
3. Writing your first Flutter APP
4. Getting started with Flutter Dart language system**
……

image

(7) Development of WeChat Mini Program

As one of the most popular programming development application scenarios, WeChat applets are very popular in the market, which makes many developers greedy. But for beginners, it's completely at a loss. I don't know what knowledge needs to be learned in the development and production of WeChat applets. Friends in need can refer to this article.

The main points of knowledge in this article:
1. Overview and introduction of
applet 2. UI development of applet
3. API operation
4. Practical combat of shopping mall projects

image

(8) Interpretation of Android-related source code

Here everyone can read this article: Niu Breaking! Ali P7 tycoon had a blast for half a month, and compiled the Android source code analysis into a 508-page PDF .

The full version of the information in the article has been organized into a PDF file, and interested friends can click here to get it quickly! Hope to help everyone!

At last

I wish you all success in your work! Happy New Year!

The road to Android development, you and I encourage each other! In 2021, let's break together!

Guess you like

Origin blog.csdn.net/BUGgogogo/article/details/113704593