hi各位亲,这篇主要说下扩展函数和枚举在开发中经常使用的知识:
一:扩展函数:
现有类的基础上,拓展一些新的功能。
系统提供了一些扩展函数,比如apply{} with{} run{}等等,最常见的是isEmptey当然自己也可以创建自己的扩展函数,如下:
//kotlin调用isEmpty()扩展函数
if (list.isEmpty()) {
}
//扩展函数begin
class testExtends {
fun testExtend1() {
var list = mutableListOf<String>()
list.add("a")
list.add("b")
list.add("c")
Log.e("fffpzf", "系统的isEmpty:" + list.isEmpty())//使用系统自己的isEmpty()扩展函数
Log.e("fffpzf", "自定义的空判断扩展函数mIsEmpty:" + list.mIsEmpty(list))//使用自己定义的mIsEmpty()扩展函数
}
//自定义扩展函数mIsEmpty(),函数也可以带参数
fun MutableList<String>?.mIsEmpty(list: MutableList<String>): Boolean {
if (this != null && this.size > 0) return false//this代表自身,MutableList<String>
if (list != null && list.size > 0) return false//使用参数
return true
}
}
===
系统的isEmpty:false
自定义的空判断扩展函数mIsEmpty:false
===
//扩展函数end
解释:
fun MutableList<String>?.mIsEmpty(list: MutableList<String>): Boolean {} :这个就是扩展函数,是对MutableList<String>的扩展,然后用?.符号,mIsEmpty(list: MutableList<String>)是扩展函数的名字和参数,当然参数是可以为空的。
使用扩展函数list.mIsEmpty(list)
二:枚举类:https://blog.csdn.net/pangzaifei/article/details/85231820
开发中一般常用枚举的when in和遍历,举例如下:
//枚举begin
enum class Week {
周一, 周二, 周三, 周四, 周五, 周六, 周日
}
class testEnum {
//1.遍历枚举
fun testWeek1() {
val values = Week.values()
values.forEach {
Log.e("fffpzf", "遍历枚举:" + it.name)
}
}
//2.when in
fun getDay(week: Week) {
when (week) {
in Week.周一..Week.周五 -> Log.e("fffpzf", "工作日...")
Week.周六 -> Log.e("fffpzf", "周六")
Week.周日 -> Log.e("fffpzf", "周日")
}
}
}
//枚举end
===
getDay:工作日...
getDay:周六
testWeek1:遍历枚举:周一
testWeek1:遍历枚举:周二
testWeek1:遍历枚举:周三
testWeek1:遍历枚举:周四
testWeek1:遍历枚举:周五
testWeek1:遍历枚举:周六
testWeek1:遍历枚举:周日
===
总结:在Android Kotlin开发中经常会用到扩展函数,我觉得是很好用的一个功能。
Ps:我是在飞~~,只有空闲时间才能更新博客,所以本系列偏快速入门,主要讲实战中经常用到内容,让你快速上手。所以文章尽量简短,敬请谅解,本系列文章默认阅读者已经熟悉java语言,希望我的博客对你有帮助!