Kotlin’s extension function

Kotlin’s extension functions are often used in everyday Android development, provided you use Kotlin. I was talking to a colleague when I finished this sentence and he said, “He doesn’t use them because he only uses Java.” I: emmm.. To ~! You’re right. Here are a few common ones that have been written down for direct use:

@kotlin.internal.InlineOnly
public inline fun <T, R> T.let(block: (T) -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block(this)
}

@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block()
    return this
}

@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.also(block: (T) -> Unit): T {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block(this)
    return this
}

public inline fun String.filter(predicate: (Char) -> Boolean): String {
    return filterTo(StringBuilder(), predicate).toString()
}
Copy the code

With these nice extension functions given to us by the authorities, we can really reduce the amount of code we need, as follows:

 val stringTo20 = "20"
 Log.e(TAG, "value:${stringTo20.toInt()}")
 

 E/MainActivity: value:20
Copy the code

Click on the toInt() method to get a look at the string-to-number method you often use

@kotlin.internal.InlineOnly
public actual inline fun String.toInt(): Int = java.lang.Integer.parseInt(this)
Copy the code

But what if we write it like this? Crash is going to happen

 val stringTo20 = "www"
 Log.e(TAG, "value:${stringTo20.toInt()}")
 
 java.lang.NumberFormatException: For input string: "www"
Copy the code

Of course, if the string is normal digital string, then our code directly use toInt (), but there are exceptions, if there is a demand from the background you can get a “number” string, ask not what I asked does not directly use json, for example, I then suddenly one day configuration and then with a wrong is not a pure digital, And you forgot to try catch and toInt(), don’t ask me why network requests don’t handle this exception, I’m just giving you an example. Development (don’t know wrong configuration) : uh, your phone poisoning? Why did the App blink back? Should we try our best to avoid this?


 val stringTo20 = "www"
 fun String.forceToInt(default: Int = 0) : Int {
        return if(this.filter { it.isDigit() }.any { this.isNotEmpty() }){
            toInt()
        }else{
            default
        }
    }
 Log.e(TAG, "value:${stringTo20.forceToInt(-1)}")
Copy the code

We can handle this situation with extension functions, which are simple and convenient.

Kotlin’s infix function

The infix symbol modifies infix functions. We usually use it to modify extension functions. Remember that there is one and only argument, for example, applying MutableLiveData

infix fun <T:Any> MutableLiveData<T>? .post(newValue:T){ this? .postValue(newValue) } infix fun <T:Any> MutableLiveData<T>? .set(newValue:T){ this? .value = newValue} // You can directly change (MutableLiveData) data to post newValue (MutableLiveData) dataset  newValue
Copy the code

This method does not bring any performance optimization, compared to the code. The execution method is more intuitive, especially for numerical calculation or merge some content, etc., do not mess with the name, otherwise it will be difficult to maintain, try to ensure that the name can be related to the function:

button translationX 200f
infix fun View.translationX(float: Float){
        translationX = float} // If it was like this, it would be hard to say translationX first, I would think view.x =float    
 button toX 200f
 infix fun View.toX(float: Float){
        translationX = float
    }

Copy the code

Unfinished, update later