Make writing a habit together! This is the fifth day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

1. Nested functions

In business development, we may encounter a scenario where a function is only called multiple times in one place and we do not want the function to be called elsewhere in the class, requiring further restrictions on access to that function.

Private is not enough, so we can use nested functions to provide better encapsulation:

fun test1(a) {

    // Restrict access to rows
    fun test2(content: String) {
        println(content)
    }

    test2("hahaha")
    test2("babababa")
    test2("uuuuuuu")}Copy the code

Only test1() can be accessed, and test2() cannot be accessed from anywhere other than test1()

However, the test2() method is too long because the test1() method is too large, so nested functions should be used selectively depending on the scenario

2.@JvmOverloadsQuick function overloading

When Android customizing a View, it usually needs to define three constructors:

class CustomView : View {
    constructor(context: Context) : super(context)
    constructor(context: Context, attributes: AttributeSet? = null) : super(context, attributes)
    constructor(context: Context, attributes: AttributeSet? = null, defStyleAttr: Int) : super(
        context,
        attributes,
        defStyleAttr
    )
}
Copy the code

@jvmoverloads loads when it’s too cumbersome to write a custom View every time:

class CustomView @JvmOverloads constructor(
    context: Context,
    attributes: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attributes, defStyleAttr) {
}
Copy the code

Decompiler into Java code:

As you can see, the Kotlin editor automatically helps us generate three overloaded constructors.

@jvMoverloads (@jvMoverloads, @jvMoverloads, @jvMoverloads, @jvMoverloads, @jvMoverloads, @jvMoverloads, @jvMoverloads, @jvMoverloads, @jvMoverloads, @jvMoverloads

3. Delay initializationlateinit var

In daily development, we use lateInit var to implement lazy initialization of attributes:

lateinit var mContent: String

mContent = "test test"
Copy the code

If we are not sure whether the attribute is initialized or not, we can use the following method to determine:

// Check if mContent is initialized
if (this::mContent.isLateinit) {
    Log.i("CustomView"."test: ")}Copy the code

4.@JvmFieldReduce generation of property set and get methods

Define a variable:

var mData: String = ""
Copy the code

Reverse to Java code:

As you can see, the compiler automatically generates the set and get methods for mData. If you don’t want to compile the set and get methods for mData, you can add @jVMField annotation:

@JvmField
var mData: String = ""
Copy the code

Decompiling into Java code:

The system won’t help us generate the get and set methods because the compiler has changed the access modifier of mData to public