一、if 和 When
1、if & When ------都可有返回值,某条件下有多行内容时------通过 **{}**进行裹起来。
2、List.withIndex()------ 返回**(index、元素)**
**3、map------**匹配List中所有元素的 xx属性值。
**4、find------**找到符合属性特定值的 元素
**5、any------**List中是否存在 某元素 满足 某条件
**6、all------**List中所有元素 满足某条件
**7、filter------**过滤 元素
Kotlindata class Product( val id: Int ,val name: String ,val price: Double ) fun main(){ // 1、定义不可变product列表 val products = listOf( Product(1,"可乐",3.5), Product(2,"矿泉水",2.0), Product(3,"方便面",5.0) ) // 2、定义购物车cart val cart = mutableListOf<Product>() cart.add(products[0]) println(cart) cart.add(products[2]) println(cart) cart.remove(products[0]) //cart.removeAt(0) println(cart) // 3、for for(product in products){ println(product.name) } // map val map_names = products.map { it.name } println("map-匹配所有元素的x属性---$map_names") // find val find_product = products.find { it.id == 2 } println("find-找到特定属性的元素---$find_product") // any & all val hasEmpty = //Boolean,存在一个满足条件 products.any { it.stock == 0 } val allEmpty=products.all { //Boolean,所有满足条件 it.stock > 0 } println("any-是否存在某属性-满足-某情况---$hasEmpty") println("all-所有元素某属性-满足-某情况---$allEmpty") val expensive = products.filter { it.price > 3 } }
二、for
一、
Kotlin// 3.1 带索引的for for((index, product) in products.withIndex()){ println("带索引------------$index ${product.name}") } val expensive = products.filter { it.price > 3 } println(expensive) // 遍历 0~4 for (i in 0 until 5) { println(i) } // 遍历 3~7 for (i in 1..5){ println(i) } // 0,2,4,6,8 for (i in 0 until 10 step 2) { println(i) } // 5,4,3,2,1 for (i in 5 downTo 1) { println(i) } // 倒序+步长:10,8,6,4 for (i in 10 downTo 2 step 2) { println(i) } // repeat 重复执行 repeat(3) { println("重试推理请求") } // 需要索引也可以直接获取 repeat(3) { index -> println("第${index + 1}次重试") }
三、MutableList
1、sumOf------=py的 sum(p.price for p in cart)
Kotlin//############创建购物车########## cart.add(products[2]) cart.add(products[2]) cart.add(products[1]) println("购物车里有如下:") for (product in cart) { println("\t${product.name} ¥${product.price}") } val total = cart.sumOf { it.price }2、业务购物车,一般,也会构建成------data class Cart