Kotlin的常用顶层函数总结

来源:互联网 发布:暮光女 出柜 知乎 编辑:程序博客网 时间:2024/06/14 11:25

kotlin和Java不一样,可以定义一些顶层函数,一些顶层函数用来可以简化一些操作,让你的代码变得更加简洁易懂,说白了也就是能装逼,这里总结一下平时用的多的。主要是4个,with,run,apply,let,also,use。

with

首先看with的定义

@kotlin.internal.InlineOnlypublic inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()

with是一个高阶函数,第二个参数是T的某个方法,返回值直接返回了执行后的结果。直接先看用法

    val textView=TextView(this)        with(textView){            text="with"            textColor=123456            background=ColorDrawable(android.R.color.transparent)        }

with主要是用来对一个对象重复操作,方便的调用方法和属性。with没有限制返回值,可以返回任何类型的变量,block中的最后一行默认就是返回值,这里返回的void 也就是Unit。这里我们直接传了一个block,我猜测编译器会把这个方法作为对应类扩展方法来直接调用。当然我们也可以这样传

    with(textView,TextView::findFocus)

直接传方法进去,不过看起来意义不大。

run

同样的定义

@kotlin.internal.InlineOnlypublic inline fun <T, R> T.run(block: T.() -> R): R = block()

用法

     textView?.run {            text="with"            textColor=123456            background=ColorDrawable(android.R.color.transparent)        }

感觉并没有太大区别,只是这里不需要多传一个参数,同样可以自己指定返回值类型,而且这里像这样写可以省去判空,是不是很方便。

apply

定义

@kotlin.internal.InlineOnlypublic inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }

用法

 textView?.apply {            text="with"            textColor=123456            background=ColorDrawable(android.R.color.transparent)        }

这里同样的的用法,不过返回值是确定的返回this。

let

定义

@kotlin.internal.InlineOnlypublic inline fun <T, R> T.let(block: (T) -> R): R = block(this)

let的定义就和之前的稍有差别了,定义里用的方法不是T类里的方法了,无法直接调用属性,返回值依然可以随意指定,这里这样使用

 textView?.let {            it?.text = "with"            it?.textColor = 123456            it?.background = ColorDrawable(android.R.color.transparent)        }

上面除了with的方法都以做用来做简单的非空判断,比如之前java的这种代码

    if(a==null)             return null;        else             return a.b();

就可以更简洁,更加优雅的写出来了。

also

@kotlin.internal.InlineOnly@SinceKotlin("1.1")public inline fun <T> T.also(block: (T) -> Unit): T { block(this); return this }

also的用法也是大同小异,用来解决在返回之前要赋值给另一个对象,或者做内部的一些操作。

use

定义

@InlineOnlypublic inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {    var closed = false    try {        return block(this)    } catch (e: Exception) {        closed = true        try {            this?.close()        } catch (closeException: Exception) {        }        throw e    } finally {        if (!closed) {            this?.close()        }    }}

这里可以看出来use是对流进行操作的,而且必须要Closeable来调用use,这里就额可以简单省去关闭流的操作。用法就不做演示了,其实都很简单。

kotlin中还有很多扩展方法,都很方便,使用最多的就是集合以及字符串的某些扩展方法,省去很多自己写遍历集合或者截取字符串等操作。

原创粉丝点击