美文网首页
google kotlin训练营-基础

google kotlin训练营-基础

作者: wwq2020 | 来源:发表于2020-07-21 22:24 被阅读0次

原文

val和var 定义变量

val定义的变量不能重新赋值,var可以

字符串

可以通过+拼接
字符串模板,variable 如果需要表达式,则{expression}

条件

val numberOfFish = 50
val numberOfPlants = 23
if (numberOfFish > numberOfPlants) {
    println("Good ratio!") 
} else {
    println("Unhealthy ratio")
}
if (fish in 1..100) {
    println(fish)
}

其他语言中switch的替代,switch

when (numberOfFish) {
    0  -> println("Empty tank")
    in 1..39 -> println("Got fish!")
    else -> println("That's a lot of fish!")
}

'

可空

var rocks: Int = null; //null can not be a value of a non-null type Int
var marbles: Int? = null; //ok
var fishFoodTreats = 6
if (fishFoodTreats != null) {
    fishFoodTreats = fishFoodTreats.dec()
}

简化版本

var fishFoodTreats = 6
fishFoodTreats = fishFoodTreats?.dec()

如果fishFoodTreats是null则使用0

fishFoodTreats = fishFoodTreats?.dec() ?: 0

添加!!,那么s如果是null则会触发NullPointerException

val len = s!!.length   // throws NullPointerException if s is null

列表,数组,循环

可以变列表

val school = listOf("mackerel", "trout", "halibut")
println(school)

可变列表

val myList = mutableListOf("tuna", "salmon", "shark")
myList.remove("shark")

val定义的可变列表,不可给这个变量重新复制,但是可以修改列表元素

数组(不可以添加删除元素)

val school = arrayOf("shark", "salmon", "minnow")
println(java.util.Arrays.toString(school))

val定义的组,不可给这个变量重新复制,但是可以修改列表元素

可以混合不同类型

val mix = arrayOf("fish", 2)

单一类型数组

val numbers = intArrayOf(1,2,3)

数组拼接

val numbers = intArrayOf(1,2,3)
val numbers3 = intArrayOf(4,5,6)
val foo2 = numbers3 + numbers
println(foo2[5])

可以数组和列表混合

val numbers = intArrayOf(1, 2, 3)
val oceans = listOf("Atlantic", "Pacific")
val oddList = listOf(numbers, oceans, "salmon")
println(oddList)

循环

val school = arrayOf("shark", "salmon", "minnow")
for (element in school) {
    print(element + " ")
}

带索引循环

for ((index, element) in school.withIndex()) {
    println("Item at $index is $element\n")
}

对数字,字母的循环

for (i in 1..5) print(i)
⇒ 12345

for (i in 5 downTo 1) print(i)
⇒ 54321

for (i in 3..6 step 2) print(i)
⇒ 35

for (i in 'd'..'g') print (i)
⇒ defg

while

var bubbles = 0
while (bubbles < 50) {
    bubbles++
}
println("$bubbles bubbles in the water\n")

do {
    bubbles--
} while (bubbles > 50)
println("$bubbles bubbles in the water\n")

repeat(2) {
     println("A fish is swimming")
}

相关文章

网友评论

      本文标题:google kotlin训练营-基础

      本文链接:https://www.haomeiwen.com/subject/uvfgkktx.html