1,数据类型转换
var a = 1
a.toChar()//转换成char
a.toShort()//转换成short
a.toInt()//转换成Int
a.toLong()//转换成Long
a.toDouble()//转换成Double
a.toFloat()//转换成Float
a.toString()//转换成String
2,when代替switch
fun count(number: Int): String =
when (number) {
1 ->
"输入内容为"
2, 3, 4 ->
"输入内容为$number,哈哈"
else ->
"输入内容为空或其他"
}
3,for循环
for (i in 11 downTo 0 step 1) {
println(i.toString())
}
downTo 到那个地方截止 条件在 in 前后的参数范围内
step 绝对值
4,list集合
(1)默认创建指定内容的集合
var list = arrayListOf<String>(“one”,"two","three","four")
(2)动态添加集合数据
var list = arrayListOf<String>()
for (i in 11 downTo 0 step 1) {
list.add(i.toString())
}
(3)集合遍历
//for 循环遍历
for(item in list){
println("this di ${item}")
}
//forEach 遍历
list.forEach { item ->
println(item)
}
// forEachIndexed 遍历 包含所有和子节点
list.forEachIndexed { index, item ->
println("this is di ${index},item is ${item}")
}
还有一些其他遍历方式,不在列举,常规forEach和forEachIndexed足够
5,Map集合
(1)默认创建指定内容的集合
val hashmap = hashMapOf<Int, String>(1 to "one", 2 to "two", 3 to "Three")
(2) 动态添加
val map = TreeMap<String, String>()
for (i in 10 downTo 1) {
var key = i.toString()
map[key] = "item" + key;
}
(3) 遍历map
for((key,value) in hashmap){
println("for === ${key},${value}")
}
hashmap.forEach { (key, value) ->
println("forEach===${key},${value}")
}