kotlin基本语法(三)函数1.4

今天我们来学习一下applay、let、with、run、lazy、user、repeat、lambda等函数
内容有点多我们可以慢慢的一个个的去学习一个开始学习
1、let函数

使用此值作为参数调用指定的函数[block]并返回其结果。
    @kotlin.internal.InlineOnly
    public inline fun <T, R> T.let(block: (T) -> R): R {
        contract {
            callsInPlace(block, InvocationKind.EXACTLY_ONCE)
        }
        return block(this)
    }
//先打印 it是打印"mylet"
//后打印 999

fun myLet():Int{
    "myLet".let{
        println(it)
        return 999
    }
}

2、applay函数
类似我们学习java中的耗时线程
.调用指定的函数[块],并将此值作为其接收器返回此值。

    @kotlin.internal.InlineOnly
    public inline fun <T> T.apply(block: T.() -> Unit): T {
        contract {
            callsInPlace(block, InvocationKind.EXACTLY_ONCE)
        }
        block()
        return this
    }
例子
  

          fun myApplay(){
                 //apply
            //    apply函数
                val task = Runnable { println("运行中") }
                Thread(task).apply { setDaemon(true) }.start()
            
                val task2 = Run
    
    nable { println("running") }
            val thread = Thread(task2)
            thread.setDaemon(true)
            thread.start()
            //let函数
        }

3、with函数
with是一个单纯的函数,并不是扩展方法

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

参数有两个,一个是T类型的receiver,类型是T.()->R的函数代码块,返回值是R类型,函数体就是传入的receiver执行block代码块。

列子
fun myWith(){
    with(ArrayList<String>()){
        add("java")
        add("kotln")
        add("c++")
        println("this = " + this)
    }.let { println(it) }
}

4、run函数
和我们刚刚说到的with函数类似
.调用指定的函数[块],并以该值作为其接收方,返回其结果。

@kotlin.internal.InlineOnly
public inline fun <T, R> T.run(block: T.() -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block()
}

例子

 fun myRun(){
        ArrayList<String>().run {
            add("aaaa")
            add("bbbb")
            add("cccc")
            println(this.joinToString())
    
        }.let { println(it) }
    }

5、lazy函数
他是一种懒惰的
这是函数表达式

public actual fun <T> lazy(initializer: () -> T): Lazy<T> = SynchronizedLazyImpl(initializer)

列子

fun myLazy(){
    fun requstJson():String="{name   age   }"
    val lazyString = lazy { requstJson() }

    val stringResult = lazyString.value
}

6、use函数
在这个资源上执行给定的[block]函数,然后正确地关闭它,不管是否抛出异常@aram阻塞一个函数来处理这个[可关闭的]资源。@返回在此资源上调用的[block]函数的结果。

   @InlineOnly
@RequireKotlin("1.2", versionKind = RequireKotlinVersionKind.COMPILER_VERSION, message = "Requires newer compiler version to be inlined correctly.")
public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
    var exception: Throwable? = null
    try {
        return block(this)
    } catch (e: Throwable) {
        exception = e
        throw e
    } finally {
        when {
            apiVersionIsAtLeast(1, 1, 0) -> this.closeFinally(exception)
            this == null -> {}
            exception == null -> close()
            else ->
                try {
                    close()
                } catch (closeException: Throwable) {
                    // cause.addSuppressed(closeException) // ignored here
                }
        }
    }
}

例子

 @RequiresApi(Build.VERSION_CODES.O)
    fun myUse(){
        val input = Files.newInputStream(Paths.get("f:\\myInformation.txt"))
        val byte = input.use {
            input.read()
        }
    }

7、repeat函数
执行指定次数的给定函数[操作]。.当前迭代的从零开始的索引作为参数传递给[action]@sample样本。混杂。控制流,重复

@kotlin.internal.InlineOnly
public inline fun repeat(times: Int, action: (Int) -> Unit) {
    contract { callsInPlace(action) }

    for (index in 0 until times) {
        action(index)
    }
}

例子

   fun myRepeat(){
        //repeat(times: Int, action: (Int) -> Unit)
        repeat(8, {println("执行")})
    }

8、lambda表达式
//语法为 {参数1,参数2…参数n ->执行的语句}
{x:Int,y:Int->x+y}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值