Kotlin – @JvmOverloads, @JvmStatic, @JvmField

Tram Ho

@JvmOverloads

Above is the code to create a custom view in Android. Quite familiar, isn’t it?

You will have no problems building. However, the unfortunate thing happens at runtime:

What is this error? The main reason in paragraph: View (context, attrs, defStyleRes)

Remember when creating a customer view class with java, we had to write 4 to 5 different constructors? In particular, the number of parameters in the constructor is different.

That is the cause of this error. Because we are missing the fun constructors needed for the View class.

-> @JvmOverLoads will solve this problem.

A case similar to the following:

With kotlin, it is possible to create an instance of MyObject with only param1 as follows:

param2 will be created with the default value.

But if we initialize the above object in java as follows, the error will be:

We must explicitly pass all parameters of the constructor, including those that already have defaults.

To solve this problem, just fix the following:

This is the description of the use of @JvmOverloads :

Quite explicit, isn’t it. It will simply help create the number of functions (or constructors) corresponding to the param value with the default value.

@JvmStatic

At first glance, it is possible to know the use of this annotation to create functions or properties in the static form.

In fact, if only pure kotlin code, we will rarely use this anno because there is one type of static definition seems more popular that is Top-level function.

However, the difference will lie in the companion object .

Usually, if we need to call these fun from another kotlin class, we just need to

However, what if you want to call them from a java class? Now @JvmStatic will have its role.

As you can see, thanks to @JvmStatic , funStatic () is called directly without any need for the class names that contain it. In contrast to funNotStatic, we must explicitly A.Companion

@JvmField

To get the value x1, do the following:

In kotlin:

In java:

java will not access variables directly but through getter and setter.

Now, we will add @JvmField as follows:

Instructs the Kotlin compiler not to generate getters / setters for this property and expose it as a field.

This anno will cancel the getter, setter of the variable, which can instead allow direct axis access. So in the above java code, it is possible to write test.x1 similar to kotlin.

Share the news now

Source : Viblo