kotlin基本语法

/*--------------------------定义函数开始-------------------------*/
    /**
     * 带有两个Int参数、返回Int的函数
     */
    fun sum(a: Int, b: Int): Int {
        return a + b
    }

    /**
     * 将表达式作为函数体、返回值类型自动推断的函数
     */
    fun sum2(a: Int, b: Int) = a + b

    /**
     * 函数返回无意义的值
     */
    fun printSum(a: Int, b: Int): Unit {
        println("sum of $a and $b is ${a + b}")
    }

    /**
     * Unit返回类型可以省略
     */
    fun printSum2(a: Int, b: Int) {
        println("sum of $a and $b is ${a + b}")
    }
    /*----------------------------定义函数结束-----------------------------*/


    /*------------------------------定义变量开始-----------------------*/
    /**
     * 一次赋值(只读)的局部变量
     */
    val a: Int = 1 // 立即赋值
    val b = 2 // 自动推断出'Int'类型

    /**
     * 可变变量
     */
    var x = 5 // 自动推断出'Int'类型

    /**
     * 顶层变量
     */
    val PI = 3.14
    var y = 0
    fun incrementY() {
        y += 1
    }
    /*--------------------------------定义变量结束---------------------------*/

    /**
     * 使用字符串模板
     */
    var s = 1
    // 模板中的简单名称
    val s1 = "s is $s"
    // 模板中的任意表达式
    val s2 = "${s1.replace("is", "was")},but now  is $s"


    /**
     * 使用条件表达式
     */
    fun maxOf(a: Int, b: Int): Int {
        if (a > b) {
            return a
        } else {
            return b
        }
    }

    fun maxOf2(a: Int, b: Int) = if (a > b) a else b


    /**
     * 使用可空值及null检测
     */
    // 当某个变量的值可以为null的时候,必须在声明处的类型后添加?来标识该引用可为空
    fun parseInt(str: String): Int? {
        return str.toIntOrNull()
    }


    // 使用返回可空值的函数
    fun printProduct(arg1: String, arg2: String) {
        val x = parseInt(arg1)
        val y = parseInt(arg2)

        // 直接使用‘x*y’会导致编译错误,因为他们可能为null
        if (x == null) {
            println("Wrong number format in arg1: '$arg1'")
            return
        }
        if (y == null) {
            println("Wrong number format in arg2: '$arg2'")
            return
        }

        // 在空检测后,x 和 y 会自动转换为非空值
        println(x * y)
    }


    /**
     * 使用类型检测及自动类型转换
     */
    fun getStringLength(obj: Any): Int? {
        if (obj is String) {
            // 'obj'在该条件分支内自动换换成'String'
            return obj.length
        }

        // 在离开类型检测分支后,'obj'仍然是'Any'类型
        return null
    }


    /**
     * 使用for循环
     */
    fun forExample() {
        val items = listOf("apple", "banana", "orange")
        for (item in items) {
            println(item)
        }
    }

    fun forExample2() {
        val items = listOf("apple", "banana", "orange")
        for (index in items.indices) {
            println("item at $index is ${items[index]}")
        }
    }


    /**
     * 使用while循环
     */
    fun whileExample() {
        val items = listOf("apple", "banana", "orange")
        var index = 0
        while (index < items.size) {
            println("item at $index is ${items[index]}")
            index++
        }
    }


    /**
     * 使用when表达式
     */
    fun describe(obj: Any): String =
            when (obj) {
                1 -> "One"
                "Hello" -> "Greeting"
                is Long -> "Long"
                !is String -> "Not a string"
                else -> "Unknown"
            } 


    /**
     * 使用区间(Range)
     */
    // 使用in运算符来检测某个数字是否在指定区间内
    fun rangeExample() {
        val x = 10
        val y = 9
        if (x in 1..y + 1) {
            println("fits in range")
        }
    }

    // 检测某个数字是否在指定区间外
    fun rangeExample2() {
        val list = listOf("a", "b", "c")
        if (-1 !in 0..list.lastIndex) {
            println("-1 is out of range")
        }
        if (list.size !in list.indices) {
            println("list size is out of valid list indices range too")
        }
    } 

    // 区间迭代
    fun rangeExample3() {
        for (x in 1..5) {
            print(x)
        }
    }

    // 数列迭代
    fun rangeExample4() {
        for (x in 1..10 step 2) {
            print(x)
        }
        println()
        for (x in 9 downTo 0 step 3) {
            print(x)
        }
    }  


    /**
     * 使用集合
     */
    // 对集合进行迭代
    fun setExample() {
        val items = listOf("apple", "banana", "orange")
        for (item in items) {
            println(item)
        }
    }

    // 使用in运算符来判断集合内是否包含某实例
    fun setExample2() {
        val items = listOf("apple", "banana", "orange")
        when {
            "orange" in items -> println("I like it.")
            "apple" in items -> println("I like it, too.")
        }
    }

    // 使用lambda表达式来过滤(filter)和映射(map)集合
    fun setExample3() {
        val fruits = listOf("apple", "banana", "orange")
        fruits.filter { it.startsWith("a") }
                .sortedBy { it }
                .map { it.toUpperCase() }
                .forEach { println(it) }
    }


    /**
     * 创建基本类及其实例
     */
    fun classExample() {
        val rectangle = Rectangle() // 不需要"new"关键字
        rectangle.setBounds(0,0,5,3)
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值