1. Use the apply, let, with functions skillfully

Like instantiating an object and assigning it a value

startActivity(Intent(activity, XXXActivity::class.java).apply {
                putExtra("XX", XXX)
                 putExtra("XX", XXX)
            })
Copy the code

Simple example: Give imageView the ability to load images directly as follows

fun ImageView.load(url: String?) {
    Glide.with(context).load(url).into(this)
}
Copy the code

use

iv_head.load("Https://ss0.bdstatic.com/70cFuhy/it/u=118307, & FM = 26 & gp = 0. 42535 JPG")
Copy the code

Another example: simplifying network requests

fun <T> Observable<ResponseBean<T>>.get(context: Context = AppManager.getInstance().currentActivity, isShowDialog: Boolean = false, message: String? = "One moment, please.", title: String? = null, next: (T?) -> Unit) {// a series of parameters this.pose (rxhttputil.handleresult <T>(context as LifecycleOwner)).subscribe(object: MySubscriber<T>(if (isShowDialog) context elsenull, message, title) { override fun onSucess(t: T?) {next(t) // callback}})}Copy the code

This is how a network request is used

Retrofit.apiService.login.get{ //it:(Loginbean)
    todo something   
}
Retrofit.apiService.login.get(isShowDialong=true,title="Tip"){//it (Loginbean) todo something} there is a collection of extension function tools available on GitHubCopy the code

Higher-order functions/closures

For example, the most common way to use activity/fragment communication is to define the interface viewModel/LiveData, and also to define the interface to implement and then force null a series of operations really bother using Koltin can do this

class TestFragment() : BaseFragment() {lateinit var next: (String) -> Unit // a function passed as a variable to the companion object {fun getInstance(next: (b: String) -> Unit): TestFragment { val fragment = TestFragment() fragment.next = nextreturn fragment
        }
    }
    
    fun sendMessageToActivity(){
        next("Send me a value.")}} //activity:BaseMvcActivity() {

    var mFramgent: TestFragment = TestFragment.getInstance {
                                                    //    it:string 
        todoSomething(it) 
    }
    
}
Copy the code

4. Date data class Lambda, etc

The data class (var id: String) mAdapter. SetOnItemClickListener {adapter, the view, the position - >}Copy the code

5. Some functions like rxJava operators such as

Iterable.map iterable. flatmap iterable. filter.... , etc.Copy the code