kotlin语法学习之动态个数参数,?:语法和let,run,with,apply,also用法

package com.example.kotlin

class Test2 {

/**
 * 动态个数参数
 * vararg
 * 数组多个元素传入函数的变长参数需要在数组名前加 * 号
 */
fun test1(vararg name: String) {
    for (item in name) {
        println(item)
    }
}

fun main(args: Array<String>) {
    test1("hello")
    test1("hello", "world")
    var arrayName = arrayOf("how", "are", "you")
    test1(*arrayName) 数组多个元素传入函数的变长参数需要在数组名前加*号
}

//-------------------------------------------------------//

/**
 * ?: 符号用法
 */
fun test2() {
    var message = null
    message ?: "hello world" // if(message !=null) message = messae else messae = "hello world"
    print(message)
}

/**
 * let 用法及作用
 * 1.判断非空
 * 2.{}内部可以用it调用message的方法
 * 3.lambada 默认返回最后一行作为返回值,如果最后一行没有返回值,就返回Unit(空)
 */
fun let() {
    val message = "abc"
    val length = message.let {
        print(it.length)
        it.length
    }
}

/**
 * with用法及使用
 * 两个参数,第一参数是个普通对象,参数没有判空
 * 第二个参数是个lambada表达式,内容可以直接使用第一个参数
 * 返回最后一行的值作为返回值
 */
fun with() {
    val message = "abc"
    val length = with(message) {
        print(message)
        print(substring(2))
        length
    }
}

/**
 * run作用
 * 1.可以像let 一样可以判空
 * 2.可以像with一样,在{}内部直接使用message的公有属性和方法
 */
fun run() {
    val message = "abc"
    val length = message.run {
        print(substring(2))
        length
    }
}

/**
 * apply 使用
 * 1.{}内部可以直接使用发起调用对象的方法
 * 2.和run不同的是,run返回最后一句。而apply返回调用者自身。这里返回添加了后的list
 */
fun apply() {
    val list = arrayListOf<String>()
    val unit = list.apply {
        add("hello")
        add("world")
    }
}


/**
 * also的用法
 * {}内部要用it替代对象来调用方法,这个和let很像
 * 不同的是 also返回的最后一句,而是返回调用者本身,这可以用来作链式调用。
 */
fun also() {
    val process = Process()
    process.also { it.step1() }.also { it.step2() }.also { it.step3() }
}

class Process {
    fun step1() {
        print("step1")
    }

    fun step2() {
        print("step2")
    }

    fun step3() = run { print("step3") }

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值