Kotlin 小细节记录(4)
57.Kotlin语言的List创建与元素获取
58.Kotlin语言的可变List集合
59.Kotlin语言的mutator函数
60.Kotlin语言的List集合遍历
61.Kotlin语言的解构语法过滤元素
62.Kotlin语言的Set创建与元素获取
63.Kotlin语言的可变Set集合
64.Kotlin语言的集合转换与快捷函数
65.Kotlin中的数组类型
66.Kotlin语言的Map的创建
67.Kotlin语言的读取Map的值
68.Kotlin语言的遍历Map
69.Kotlin语言的可变Map集合
70.Kotlin语言的定义类与field关键字
71.Kotlin语言的 计算属性 与 防范竞态条件
72.Kotlin语言的主构造函数
73.Kotlin语言的主构造函数里定义属性
74.Kotlin语言的次构造函数
75.Kotlin语言的构造函数中默认参数
76.Kotlin语言的初始化块
77.Kotlin语言的构造初始化顺序
78.Kotlin语言的延迟初始化lateinit
79.Kotlin语言的惰性初始化by lazy
80.Kotlin语言的初始化陷阱
基础遍历,防止崩溃getOrElse/getOrNull
val list = listOf("A","B","C","D")
println(list[3])
// 防止崩溃方式
println(list.getOrElse(5){"越界"})
println(list.getOrNull(5)?:"your out of bound")
不可变集合与可变集合互相转换,toList,toMutableList
val mlist = mutableListOf("A","B","C")
mlist.add("D")
mlist.remove("A")
//不可变集合变成可变集合
val list2 = list.toMutableList()
list2.add("E")
// 可变集合 变成 不可变
val list3 = mlist.toList()
// 运算符重载,add remove
val list4 = mutableListOf("A","B","C","D")
list4 += "AA"
list4 -= "A"
println(list4)
动态移除removeIf,和获取下标的遍历 forEachIndexed,+=和-=可变数组的操作符重载
// removeIf
val list5 = listOf("A","B")
list4.removeIf{list5.contains(it)}
println(list4)
// 遍历
for (s in list) {
println(s)
}
list.forEach{
println(it)
}
list.forEachIndexed{s,i->
println("item ${s} index ${i}")
}
val listNull = listOf<String>()
val ttt = listNull.getOrNull(0)
ttt.apply {
if(this == null) {
println("null")
}
}
ttt?.apply {
println("aaaaa")
}
解构
val vlist = listOf("A","B","C")
// 解构
var (v1,v2,v3) = vlist
println("$v1,$v2,$v3")
// 过滤结构赋值
val (_,n1,n2) = vlist
val(_,t2,t3) = Triple(1,2,3)
Set 集合不允许重复,操作和list类似,比较有用的越界保护
fun main() {
val set:Set<String> = setOf("aaa","bbb","ccc","ccc")
println(set)
println(set.elementAt(0))
println(set.elementAt(1))
println(set.elementAt(2))
println(set.elementAtOrElse(3) { "越界了" })
println(set.elementAtOrNull(3)?:"out of bounds")
val mutableSet:MutableSet<String> = mutableSetOf("AAA","BBB")
mutableSet += "David"
mutableSet += "zcw"
mutableSet -= "David"
mutableSet.add("zcwfeng")
mutableSet.remove("zcw")
println(mutableSet)
}
数组操作,arrayOf事对象类型,越界保护
intArrayOf()
doubleArrayOf()
floatArrayOf()
longArrayOf()
charArrayOf()
byteArrayOf()
booleanArrayOf()
shortArrayOf()
emptyArray<Unit>()
ubyteArrayOf()
uintArrayOf()
ulongArrayOf()
ushortArrayOf()
fun main() {
val inArray = intArrayOf(1,2,3,4,5)
println(inArray[4])
println(inArray.elementAtOrElse(5){-1})
println(inArray.elementAtOrNull(5)?:"越界了")
val charArray = listOf('A','B','C').toCharArray()
val objArray/*:Array<File>*/ = arrayOf(File(""),File(""))
}
Map 操作,getOrPut有些场景很方便,可以放入Pair做key,value
val map = mapOf<String,Double>("David" to(12.34) ,"Lucy" to 123.44)
val map2 = mapOf(Pair("David",12.34),Pair("Lucy",123.44),"AAA" to 22.22)
println(map["David"])
println(map.getOrDefault("David","test"))
println(map.getOrElse("Lucy0") { "test" })
map2.forEach {
println("Key->${it.key},value->${it.value}")
}
map2.forEach { (key,value) ->
println("Key->${key},value->${value}")
}
for (entry in map2) {
println("Key->${entry.key},value->${entry.value}")
}
val map3 = mutableMapOf(Pair("David",12.34),Pair("Lucy",123.44),"AAA" to 22.22)
map3 += "AAAA" to 7777.0
map3 -= "AAAA"
map3.put("CCC",0.3)
map3.getOrPut("FFF"){444.44}//判断有没有,有返回,没有加入
println(map3)
类默认field 的set和get。 get() 覆盖field内容,防范竞态条件
class Person{
var name = "zcwfeng"
/*set(value) {
field = value
}
get() = field*/
var info:String? = ""//"ddd"//null/*"be success!"*/
val number : Int
get() = (1..1000).shuffled().first()
// 防范竞态条件,Kt的编程规范
fun getShowInfo():String{
return info?.let {
if(it.isBlank()){
"空串"
} else {
"最终info是:${info}"
}
}?: "你是null,注意"
}
}
fun main() {
println(Person().number)
println(Person().getShowInfo())
}
主构造函数,定义属性
// 主构造函数,参数不能直接使用
class User(_name: String, _sex: Char, _age: Int, _info: String) {
var name = _name
get() = field
set(value) {
field = value
}
var age = _age
get() = field + 1
val sex = _sex
get() = field
val info = _info
get() =
field.let {
if (it.isNullOrBlank()) {
""
} else {
"[$field]"
}
}
fun show() {
println(name)
}
}
//简写
class User2(var name: String, var sex: Char, var age: Int, var info: String){
fun show() {
println(name)
println(sex)
println(age)
println(info)
}
}
fun main() {
val p = User(_name = "zcw", _sex = 'M', _age = 18, _info = "aaa")
println(p.name)
println(p.info)
User2(name = "zcw", sex = 'M', age = 18, info = "aaa").show()
}
init 代码块初始化检测require, init 代码块和累成员变量是并列关系,先写谁先执行谁
class User3(var name:String = "1" ){
init {
println(name)
require(!name.isNullOrBlank()){
println("初始化空")
}
}
constructor(name:String = "2", sex:Char) : this(name) {
println("constructor(name:String, sex:Char)")
}
constructor(name:String = "3", sex:Char,age:Int) : this(name) {
println("constructor(name:String, sex:Char,age:Int)")
}
constructor(name:String = "4", sex:Char,age:Int,info: String) : this(name) {
println("(name:String, sex:Char,age:Int,info: String)")
}
}
lateinit 使用保护注意,使用过程可能会漏掉初始化,所以注意判断保护。
lateinit var demo3:String
fun show(){
if(::demo3.isInitialized){
println(demo3)
}else {
println("你忘记初始化")
}
}
by lazy 惰性加载,区别直接加载
class P{
val demo4 = testByLazy()
val demo5 by lazy { testByLazy() }
private fun testByLazy():String{
println("test")
println("test")
println("test")
println("test")
return "result is OK"
}
}
val p = P()
Thread.sleep(5000)
println("will be used")
// println(demo4)
println("${p.demo5}")
kotlin 顺序的潜在bug,非常小心, 注释中的第一行和最后一行互换测试
class MyContent(_info:String){
// val content:String = getMyInfo()
private val info = _info
private fun getMyInfo():String = info
val content:String = getMyInfo()
}
fun main() {
println(MyContent("david").content.length)
}
可变参数,遍历可以不加?判断
fun recycleBitmap(vararg bitmaps: String?) {
bitmaps.apply {
for (bm in this) {
bm?.apply {
println("axiba")
}
}
}
}
var demos:String? = "null"
var demos:String? = null
recycleBitmap(demos)