美文网首页
Kotlin-补充

Kotlin-补充

作者: 陈饥饿 | 来源:发表于2022-03-11 10:16 被阅读0次

    1、字符串内嵌表达式

    1.1、Kotlin中内嵌表达式的语法规则

    "hello, ${obj.name}. nice to meet you!"

    Kotlin允许我们在字符串里嵌入${}这种语法结构的表达式,并在运行时使用表达式执行的结果替代这一部分内容。

    1.2、当表达式中仅有一个变量的时候,还可以将两边的大括号省略。

    "hello, $name. nice to meet you!"

    2、函数的参数默认值

    2.1、次构造函数在Kotlin中很少用,因为Kotlin提供了给函数设定参数默认值的功能,它在很大程度上能够替代次构造函数的作用。

    2.2、我们可以在定义函数的时候给任意参数设定一个默认值,这样当调用此函数时就不会强制要求调用方为此参数传值,在没有传值的情况下会自动使用参数的默认值。

    fun printParams(num: Int, str: String = "hello"){

        println("num is $num, str is $str")

    }

    fun main(){

        printParams(123)

    }

    2.3、Kotlin提供了可以通过键值对的方式来传值的机制,从而不必按照参数定义的顺序来传参。

    printParams(str = "str", num = 123)

    2.4、参数默认值可以在很大程度上替代次构造函数的作用。

    class Student(val sno: String, val grade: Int, name: String, age: Int) : Person(name, age){

        constructor(name: String, age: Int) : this("", 0, name, age){

        }

        constructor() : this("", 0){

        }

    }

    改写之后:

    class Student(val sno: String = "", val grade: Int = 0, name: String = "",age: Int = 0) : Person(name, age){

    }

    相关文章

      网友评论

          本文标题:Kotlin-补充

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