kotlin基础语法

327 阅读2分钟

kotlin基础语法

kotlin基本数据类型

数值类型

类型 位宽度
Int 32
Long 64
Float 32
Double 64
Short 16
Byte 8

字符 在kotlin中,char不能直接和数值进行操作。

fun switch(c: Char) {
    if (c == 1) { // 错误:类型不兼容
        // todo
    }
}

布尔

布尔类型包含true和false

数组

kotlin中的数组使用类Array实现,与java不同的是,kotlin可以使用[]来替代java中的get和set操作。 数组有两种创建方式:

var arr1 = arrayOf(1, 2, 3)
var arr2 = Array(3) { item -> (item + 1) } //[1,2,3]

字符串

kotlin中的String同样也是不可变的,同时kotlin中的string也支持使用[]来访问每一个字符。

kotlin支持使用"""来显示多行字符串

var str = """
    abcdefg
    hijklmn
    opqrst
    uvwxyz
""".trimIndent()

变量声明

在kotlin中声明变量只提供了两个关键字,var和val。其中var用以声明可变变量,val用以声明不可变变量

//可变变量
var a = 1 //类型自动推断
var b: Boolean = false
//不可变变量,它们的值不可被修改
val c = 2
val d: Boolean = true

函数声明

在kotlin中函数的声明使用fun关键字,同java不同的是,kotlin变量的类型放在变量之后,返回值也同样放在方法名之后。

有返回值的函数

fun add(a: Int, b: Int): Int {
    return a + b
}

无返回值的函数(note:kotlin中无返回值的函数其实是返回Unit类型,默认可以省略)

fun printHello() {
    print("hello")
}

可变长参数函数 函数的变长参数需要使用vararg关键字

fun printVararg(vararg list: String) {
    for (item in list) {
        println(item)
    }
}

lambda匿名函数

val add2: (a: Int, b: Int) -> Int = { a, b -> a + b }

循环

for循环

在kotlin中,for循环可以对所有支持迭代器的对象进行遍历。

    //直接打印
    for (item in arr1) {
        println(item)
    }

    //通过索引打印
    for (i in arr1.indices) {
        println(arr1[i])
    }

    //同时打印索引和数值
    for ((index, value) in arr1.withIndex()) {
        println("$index : $value")
    }

while 和 do...while循环

这两种循环基本可以看做是一样的,不同的是do...while至少会执行一次。

fun testWhile() {
    var n = 1;
    do {
        println("do...while loop")
    } while (n > 1)

    while (n > 1) {
        println("while loop")
    }
}

执行上面的函数会打印

do...while loop

跳转和返回

kotlin同java一样,也提供了break、continue和return,作用也同java一样。

类和对象

kotlin中类可以包含:构造函数和初始化代码块、函数、属性、内部类、对象声明。 kotlin使用class来声明类。

class Car {
    //里面包含类的构成
    var arg1 : Int = 1 //属性
    fun function1(){} //成员函数
}

//可以存在空类
class Empty

如果想使用类不需要new关键字

var car=Car()
    car.arg1 = 2 //使用.来调用属性
    car.function1() //使用.来调用函数
class Cat(name: String) {
    constructor(name: String, age: Int) : this(name) //次构造函数
}