Kotlin扩展函数和扩展属性
2019-09-18 本文已影响0人
儿歌八万首
Kotlin 可以对一个类的属性和方法进行扩展,对被扩展的类代码本身不会造成任何影响。
扩展函数可以为已经存在的类添加新的方法,并且不会修改原来的类。
扩展函数由一下几个模块组成:
//Type:表示要扩展的类
//functionName:表示扩展函数的方法名
fun Type.functionName(){
//扩展函数的逻辑
}
具体使用可以看下面的例子,我们定义一个String类的扩展函数,tolenght()来获取字符串的长度。
//自定义扩展函数实现获取字符串的长度
fun String.tolenght(): Int {
return length
}
//具体使用方法,等价于 "张山".length
"张山".tolenght()
扩展函数和普通函数一样也可以有参数和返回值的,比如下面这个我们定义一个list中添加对象,addBy(),向对于list.add()方法多了一个返回值,这样我们就可以采用链式调用了,具体代码:
//添加一个对象到集合中,并且返回这个集合
fun <T> MutableList<T>.addBy(t: T): MutableList<T> {
this.add(t)
return this //返回集合本身
}
扩展属性
//自定义扩展属性,
var <T> MutableList<T>.lastData: T
//获取集合中最后一个对象
get() = this[this.size - 1]
//设置集合中最后一个对象的值
set(value) {
this[this.size - 1] = value
}
具体用法,定义一个String类型的集合,然后通过lastData来改变或者获取集合中的最后一个对象
val strs = mutableListOf<String>()
strs.lastData = "dd"
var mo = strs.lastData
自定义扩展属性不能设置初始值,且主要是通过get,set方法来获取或者修改属性的值。
另外,谷歌也推出了Kotlin KTX(就是把比较常用的一些代码块,利用kotlin扩展函数进行封装,然后在这个基础上,提供更良好的 API,供开发者使用 ),具体用法可以参考 android ktx
这里提供一个项目中用到的部分扩展函数代码:
//字符串转换成double
fun String.toDoubleNum(): Double {
return if (this.isNotEmpty()) {
try {
this.toDouble()
} catch (e: Exception) {
0.0
}
} else {
0.0
}
}
//字符串转换成Int
fun String.toIntNum(): Int {
return if (this.isNotEmpty()) {
try {
this.toInt()
} catch (e: Exception) {
0
}
} else {
0
}
}
//字符转换泛型对象
inline fun <reified T> String.toBean(): T {
return GsonUtils.toBean(this, T::class.java)
}
//拼接多个字符串设置给textView
fun TextView.setTexts(vararg strs: String) {
val strBuffer = StringBuffer()
for (str in strs) {
strBuffer.append(str)
}
this.text = strBuffer.toString()
}
//设置网络图片
fun ImageView.setImageUrl(url: Any, empty: Int) {
GlideUtils.showNormalCenterCropImage(url, this, empty)
}
//判断是否网络图片
fun String.isNetWorkImage(): Boolean {
return this.contains("http:/") || this.contains("https:/")
}
//中间toast
fun String.toastCenter() {
ToastUtils.setGravity(Gravity.CENTER, 0, 0)
ToastUtils.setBgColor(BaseLibraryApplication.getBaseApplication().resources.getColor(R.color.black_three))
ToastUtils.setMsgColor(BaseLibraryApplication.getBaseApplication().resources.getColor(R.color.white))
ToastUtils.showShort(this)
}
//底部toast
fun String.toastBottom() {
ToastUtils.setGravity(Gravity.BOTTOM, 0, 0)
ToastUtils.setBgColor(BaseLibraryApplication.getBaseApplication().resources.getColor(R.color.black_three))
ToastUtils.setMsgColor(BaseLibraryApplication.getBaseApplication().resources.getColor(R.color.white))
ToastUtils.showShort(this)
}
//qmuiTipDialog
fun String.showTipDialog(context: Context) {
val tipDialog = QMUITipDialog.Builder(context)
.setTipWord(this)
.create(true)
tipDialog.setCanceledOnTouchOutside(true)
tipDialog.show()
Timer().schedule(object : TimerTask() {
override fun run() {
tipDialog.dismiss()
}
}, 2000)
}
//修改文件名称
fun String.modifierFileName(): String {
var fileNames = this.split(".")
if (fileNames.size == 2) {
return fileNames[0] + TimeUtils.getNowMills() + "." + fileNames[fileNames.size - 1]
} else {
return this
}
}