1. 函数定义
fun main(a: Int, s: String): Int{
val a = 1
println("a = ${a}"
return a
}
主函数 main,关键字 fun,: 后跟返回的类型,${val}字符串模板取对应值。val 定义常量,var 定义变量
2. 基本类型
a: Int s: String number: IntRange 数值范围类型,如:val diceRange = 1…6
3. 创建类
var dice = Dice(6)
class Dice(val numSides: Int){
fun roll(): Int{
return (1..numSides).random()
}
}
外部可直接调用dice.numSides获得实例化的参数
4. 条件语句
val num = 4
if (num > 4) {
println("The variable is greater than 4")
} else if (num == 4) {
println("The variable is equal to 4")
} else {
println("The variable is less than 4")
}
val luckyNumber = 4
when (rollResult) {
luckyNumber -> println("You won!")
1 -> println("So sorry! You rolled a 1. Try again!")
2 -> println("Sadly, you rolled a 2. Try again!")
...
else -> println("Else Situation")
}
when: rollResult 和 ->前面的值比较
|