让你的代码更具kotlin风味(适合java转kotlin开发者)

让你的代码更具kotlin风味(适合java转kotlin开发者)

用高阶函数和lambda表达式代替callback

1.定义

object MIAudioResourceManager {
    init {
        Log.d(TAG, "MIAudioResourceManager")
    }
    
    fun testCallBack(text: String?, callback: (str: String, number: Int) -> Unit, errorCallback: ((str: String) -> Unit)?) {
        text?.apply { callback("success , text = $this", 1) }
                ?: errorCallback?.invoke("fail , text = $text")

        //等价于
        /*if (text == null) {
            errorCallback?.invoke("fail , text = $text")
        } else {
            callback("success , text = $text", 1)
        }*/
    }
}

2.调用

           MIAudioResourceManager.testCallBack("123",
                    { str, number ->
                        Log.d(TAG, "str = $str ,number =$number")
                    },
                    null
            )
            MIAudioResourceManager.testCallBack( null,
                    { str, number ->
                        Log.d(TAG, "str = $str ,number =$number")
                    },
                    {
                        Log.d(TAG, "str = $it")
                    }
            )

使用标准库函数

1.takeif,run,apply,aslo,let

lastPresentation?.takeUnless { it.mContentViewType == type}?.run {
  	mLifecycleRegistry?.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    mContentViewType
    }?.let { finishIotPA(it) }
 fun render(view: View, item: Item) = with(view) {
        if (item !is MediaItem) {
            throw AssertionError("Item is not an instance of MediaItem")
        }

        showMedia(item.media)
        reset()
    }

在这里插入图片描述
T.()->Unit里的this代表的是自身实例,
而(T)->Unit里,this代表的是外部类的实例,it指向参数T类型实例

使用when

fun access(contract: Contract,employee: Employee) = when (contract to employee) {
    PROBATION to SENIOR_ENGINEER,
    PROBATION to REGULAR_ENGINEER -> NotGranted(AssertionError("Access not allowed on probation contract."))
    PERMANENT to SENIOR_ENGINEER,
    PERMANENT to REGULAR_ENGINEER,
    PERMANENT to JUNIOR_ENGINEER,
    CONTRACTOR to SENIOR_ENGINEER -> Granted(DateTime(1))
    CONTRACTOR to REGULAR_ENGINEER,
    PROBATION to JUNIOR_ENGINEER,
    CONTRACTOR to JUNIOR_ENGINEER -> Blocked("Access for junior contractors is blocked.")
    else -> throw AssertionError("Unsupported case of $employee and $contract")
}
 fun render(view: View, item: Item) = with(view) {
        if (item !is MediaItem) {
            throw AssertionError("Item is not an instance of MediaItem")
        }

        showMedia(item.media)
        reset()
    }
发布了22 篇原创文章 · 获赞 14 · 访问量 3075
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览