让你的代码更具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()
}
362


&spm=1001.2101.3001.11974&articleId=104000468&d=1&t=3&u=52525a25fd7c49e192a7df2bfef0f834)

被折叠的 条评论
为什么被折叠?



