Kotlin基础语法

2018-09-19  本文已影响0人  512DIDIDI
/*表达式函数 返回类型自动推导*/
fun sum(a: Int, b: Int, c: Int) = a + b + c
/*unit就是void 默认不用写*/
fun printSum(a: Int): Unit {
    println(a)
}
/*可变长参数函数*/
fun vars(vararg v: Int) {
    /*foreach*/
    for (vt in v) {
        print("$vt ")
    }
}
fun printNullException(age: String?) {
    /*抛出空指针异常*/
    println(age!!.toInt())
}

fun notPrintNullException(age: String?) {
    /*空指针不做处理返回值*/
    println(age?.toInt())
}

fun printNullReturn(age: String?) {
    /*空判断处理 如果为空则返回-2*/
    println(age?.toInt() ?: -2)
}
/*
* lambda表达式
* val 相当于final var可变变量类型
* (在类中声明属性时 val只提供getter仅供查询,var则多提供一个setter可写入)
* */
val sumLambda: (Int, Int) -> Int = { x, y -> x + y }
fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        /*做过类型判断后 obj转为String类型 调用的是String的length()方法*/
        return obj.length
    }
    return null
    /*判断了obj非非String后 obj就可以显式转换为String*/
    /*if(obj !is String)
        return null
    return obj.length*/
    /*&&右侧 obj会被自动转为String类型*/
    /*if (obj is String && obj.length>0){
        return obj.length
    }
    return null*/
}
fun printRangeNum(threshold: Int) {
    print("0..threshold: ")
    for (i in 0..threshold) {//i in [0,threshold]
        print(i)
    }
    print("\nthreshold..0: ")
    for (i in threshold..0) {//i in [threshold,0]
        print(i)
    }
    print("\n0..threshold step 2: ")
    for (i in 0..threshold step 2) {//添加步长
        print(i)
    }
    print("\nthreshold down to 0 step 2: ")
    for (i in threshold downTo 0 step 2) {//从大到小
        print(i)
    }
    print("\n0 until threshold: ")
    for (i in 0 until threshold) { //i in [0,threshold)
        print(i)
    }
}
fun printString(name:String){
   /*字符串模板编译后创建了一个StringBuilder,把常量与变量附加了上去*/
  println("hello $name")
}
上一篇下一篇

猜你喜欢

热点阅读