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

1.@JvmNameChange method name

Look directly at examples:

    @JvmName("testCopy")
    fun test(name: String, age: Int){}Copy the code

Direct decompilation into Java code to look at:

The resulting method name is testCopy, not test

2.@get:JvmName,@set:JvmNameModifying the property name

@get: JvmName("getSource")
@set: JvmName("setSource")
var mData: String = ""
Copy the code

Direct decompilation into Java code to look at:

For the val attribute, you can only use @get: JvmName

3.String nullity is usedisNullOrEmptyTo avoidTextUtils.isEmpty()

Let’s compare these two ways:

Textutils.isempty () does not call name.length, but textutils.isempty () does. Don’t empty `

Error: isNullOrEmpty () : isNullOrEmpty ();

@kotlin.internal.InlineOnly
public inline funCharSequence? .isNullOrEmpty(a): Boolean {
    contract {
        returns(false) implies (this@isNullOrEmpty! =null)}return this= =null || this.length == 0
}
Copy the code

IsNullOrEmpty has a contract in the body of the isNullOrEmpty method. This contract helps the compiler to tell whether String is empty or not, so that when name.length is called the compiler can infer that String is not empty. Is not empty

4. Ignore case comparisonequals

General case comparison is as follows:

val res = "aa".toLowerCase(Locale.ROOT) ==  "AA".toLowerCase(Locale.ROOT)
Copy the code

Decompiler into Java code:

As you can see, “aa”.tolowerCase (locale.root) is assigned to a local variable var6, and “aa”.tolowercase (locale.root) is assigned to another local variable var7, which is then compared.

This way of comparing creates two additional local String variables, so it is recommended to use equals instead, where the second argument can specify that case comparisons are ignored

val res = "aa".equals("AA", ignoreCase = true)
Copy the code

The compiler:

As you can see, the implementation is very simple and no additional local variables are created

5. Operator overloadget,set

  • get
class Pro {
    operator fun get(content: String): String {
        return content.repeat(10)}}Copy the code

Then you can use: println(Pro()[“blue”])

  • set
operator fun set(key: String, value: String){}Copy the code

The set operator overload requires at least two arguments, using the following: Pro()[“key”] = “value”

These two operators are used in many scenarios, such as read and write encapsulation for SharedPreference in Android. For details, please refer to article 3. A combination of delegate and Share Preference

There are many other operator overload functions, such as plus corresponding to “+”, contains corresponding to “in” and so on, are more commonly used in daily development, you can flexibly use according to specific scenarios