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") }
}
}