The Kotlin extension function

Kotlin’s ability to extend new functionality to a class without inheriting it or using design patterns like decorators makes it possible to write a new function for a class from a third-party library that you can’t modify. This new function can be called as a normal method, just like the original one. In Android development, we can do extension processing for the API frequently used by Android combined with business, and then we can achieve the full use of API logic related to some business.

For example, an extension to the ViewMdoel object context transformation in fragments

inline fun <reified T : ViewModel> Fragment.viewModel(
    factory: ViewModelProvider.Factory,
    body: T.() -> Unit
): T {
    val vm = ViewModelProviders.of(this, factory)[T::class.java]
    vm.body()
    return vm
}
Copy the code

Today we have an extension to the basic data type Boolean

Purpose: To enable us to use the process more in line with the logical thinking of reading, more simple, do not use if else(plaintext) expression, first code and test cases:

Code: BooleanEtx. Kt

package com.kpa.component.ui.extension

/ * * *@author: kpa
 * @time: 2021/4/17
 * @email: billkp@yeah.net
 **/

/**
 * 数据
 */
sealed class BooleanExt<out T>

object Otherwise : BooleanExt<Nothing> ()class WithData<T>(val data: T) : BooleanExt<T>()

/** * Execute block */ when the condition is true
inline fun <T : Any> Boolean.yes(block: () -> T) =
    when {
        this -> {
            WithData(block())
        }
        else -> {
            Otherwise
        }
    }

/** * Execute block ** / when the condition is false
inline fun <T> Boolean.no(block: () -> T) = when {
    this -> Otherwise
    else -> {
        WithData(block())
    }
}

/** * Block */ is executed when the condition is mutually exclusive
inline fun <T> BooleanExt<T>.otherwise(block: () -> T): T =
    when (this) {
        is Otherwise -> block()
        is WithData -> this.data
    }
Copy the code

Test cases:

@Test
fun addition_isCorrect(a) {
    true.yes { 
        // doSomething
    }
    false.no{
        // doSomething
    }
    // Return a value (conditional true)
    val otherwise = getBoolean().yes {
        2
    }.otherwise {
        1
    }
    assertEquals(otherwise, 2)
    // Return value (condition false)
    val otherwise1 = false.no {
        2
    }.otherwise {
        3
    }
    assertEquals(otherwise1, 2)}fun getBoolean(a) = true
Copy the code

Conclusion:

We can write the logic directly to the business at work, and we use inline functions, so we are if else at the bytecode level, so we don’t have to worry about security and simplify the code. The only added overhead is creating the data return class WithData, which is of course negligible in our development.