美文网首页Kotlin
Kotlin basic syntax(科特林基本语法)

Kotlin basic syntax(科特林基本语法)

作者: Air_w | 来源:发表于2019-05-22 18:22 被阅读0次
    Kotlin basic syntax(科特林基本语法)

    目录一览:
    1、Defining packages
    2、Defining functions
    3、Defining variables
    4、Comment
    5、Using string templates
    6、Using conditional expressions
    7、Using nullable values and checking for null
    8、Using type checks and automatic casts
    9、Using a for loop
    10、Using a while loop
    11、Using when expression
    12、Using ranges
    13、Using collections
    14、创建类以及实例

    1、Defining packages(定义包)

    package my.demo
    
    import java.util.*
    //应该在文件的头部指定包
    //....
    

    2、Defining functions(定义函数/方法)

    //拥有两个Int类型的参数,以及一个Int的返回类型
    fun sum(a: Int, b: Int): Int {
        return a + b;
    }
    
    //具有表达式主体和推断返回类型的函数:
    fun sum(a: Int, b: Int) = a + b;
    
    sum(5,6);//Result = 5+6;
    
    //函数返回没有意义的值(概念同:没有返回值,或返回值为空)
    fun sumReturnNoMeaningful(a: Int, b: Int): Unit {
        println("sum of a and b is ${a + b}");
    }
    
    //可省略的Unit:函数返回没有意义的值(概念同:没有返回值,或返回值为空)
    fun sumReturnOmitted(a: Int, b: Int) {
        println("sum of a and b is ${a + b}");
    }
    

    3、Defining variables(定义属性)

    3.1不可变属性(常量,用val修饰)
    3.2可变属性(变量,用var修饰)

    /*
    /*
    常量使用val修饰
     */
    val a: Int = 1  // 定义一个显式的Int类型的常量a
    val b = 2   // 根据2推断出:b是一个Int的常量
    val c: Int  // 当属性未初始化数据时,此时必须显式地声明属性的类型
    println(c);//无法通过编译(在调用属性前需要赋值)
    c = 3       // 延期赋值
    println(c);//正常通过编译
    
    /*
    变量使用var修饰
     */
    var x = 5 // 当为属性赋默认值时,编译器可推算出属性的类型
    x += 1
    println(x);
    

    4、Comment(注释)

    4.1、同Java、JavaScript,Kotlin支持相同的注释
    4.2、与Java不同,Kotlin中的块注释可以嵌套。

    // This is an end-of-line comment
    
    /* This is a block comment
       on multiple lines. */
    
        /*
        This is nest block comment->start.
    
        /*
        This is first block comment.
         */
    
        /*
        This is second block comment.
         */
    
        This is nest block comment->end.
         */
    

    5、Using string templates(使用字符串)

    
        var a = 1
        // (任意名称)simple name in template:
        val s1 = "a is $a"
    
        a = 2
        // (任意表达式)arbitrary expression in template:
        val s2 = "${s1.replace("is", "was")}, but now is $a"
        
    

    6、Using conditional expressions(使用条件表达式)

    fun maxOf(a: Int, b: Int): Int {
        if (a > b) {
            return a
        } else {
            return b
        }
    }
    
    fun maxOf(a: Int, b: Int) = if (a > b) a else b
    

    7、Using nullable values and checking for null(使用可为空的值,并检查是否为空)
    描述:当null值可能时,必须将引用明确标记为可为空,"?"代表nullable

    //如果str不支持Int类型,则返回null
    fun parseInt(str: String): Int? {
        // ...
    }
    
    //
    fun printProduct(arg1: String, arg2: String) {
        val x = parseInt(arg1)
        val y = parseInt(arg2)
    
        // 使用x,y会产生错误,因为他们支持为null,因此执行null校验
        if (x != null && y != null) {
            // x and y are automatically cast to non-nullable after null check
            println(x * y)
        }
        else {
            println("either '$arg1' or '$arg2' is not a number")
        }    
    }
    

    or

    // ...
    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)
    

    8、Using type checks and automatic casts(使用类型检查和自动转换)

    fun getStringLength(obj: Any): Int? {
        if (obj is String) {
            // `obj` is automatically cast to `String` in this branch
            //obj 自动转换成 String类型
            return obj.length
        }
    
        //在转换体外部时,'obj'依然是Any类型
        obj//Any type.
        return null
    }
    

    or

    fun getStringLength(obj: Any): Int? {
        if (obj !is String) return null
    
        // `obj` is automatically cast to `String` in this branch
        return obj.length
    }
    

    or even

    fun getStringLength(obj: Any): Int? {
        // `obj` is automatically cast to `String` on the right-hand side of `&&`
        if (obj is String && obj.length > 0) {
            return obj.length
        }
    
        return null
    }
    

    9、Using a for loop(使用for循环)
    描述:1、遍历内容(item)
    描述:2、遍历索引(index)

        /*
        遍历元素
         */
        val items = listOf("apple", "banana", "kiwifruit")
        for (item in items) {
            println(item)
        }
    

    or

        /*
        遍历索引
         */
        val items = listOf("apple", "banana", "kiwifruit")
        for (index in items.indices) {
            println("item at $index is ${items[index]}")
        }
    

    10、Using a while loop(使用while循环)

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

    11、Using when expression(使用when表达式)

        /*
        传入参数类型:Any,返回值参数类型:String
         */
        fun describe(obj: Any): String =
            when (obj) {
                1 -> "One"
                "Hello" -> "Greeting"
                is Long -> "Long"
                !is String -> "Not a string"
                else -> "Unknown"
            }
        //调用函数
        val result: String = describe(1);
    

    12、Using ranges(区间)
    描述:1、检查是否在区间内
    描述:2、检查是否超出区间
    描述:3、在区间内进行遍历

    检查数是否在区间中

        /*
        检查数是否在区间中
         */
        val x = 10
        val y = 9
        if (x in 1..y+1) {
            println("fits in range")
        }
    

    检查是否超出区间

        /*
        检查是否超出区间
         */
        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")
        }
    

    在区间内进行迭代、遍历

        /*
        在区间范围内迭代、遍历
         */
        for (x in 1..5) {
            print(x)
        }
    
        for (x in 1..10 step 2) {
            print(x)
        }
        println()
        for (x in 9 downTo 0 step 3) {
            print(x)
        }
    

    13、Using collections(使用集合)
    描述:1、迭代集合
    描述:2、检查集合是否包含某对象
    描述:3、使用lambda表达式过滤集合

    迭代集合(Iterating over a collection:)

    for (item in items) {
        println(item)
    }
    

    检查集合是否包含某对象(Checking if a collection contains an object using in operator:)

    when {
        "orange" in items -> println("juicy")
        "apple" in items -> println("apple is fine too")
    }
    

    使用lambda表达式过滤集合(Using lambda expressions to filter and map collections:)

    val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
    fruits
      .filter { it.startsWith("a") }
      .sortedBy { it }
      .map { it.toUpperCase() }
      .forEach { println(it) }
    

    14、创建类以及实例

    val rectangle = Rectangle(5.0, 2.0) //no 'new' keyword required
    val triangle = Triangle(3.0, 4.0, 5.0)
    

    想要查看更多、更详细有料干货点击我https://pdliuw.github.io/

    相关文章

      网友评论

        本文标题:Kotlin basic syntax(科特林基本语法)

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