Kotlin笔记11-Kotlin新特性-字符内嵌表达式,函数的参数默认值


6. Kotlin新特性

  • 字符内嵌表达式

$

序号

Tips

1

摆脱字符串联

​内嵌表达式语法规则:​

class Obj {
val name = ""
val age = 0
}
"hello, ${obj.name}. nice to meet you!"

​仅有一个变量:​

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

​Example:​

val zero = "hello," + name + ".name to meet you." + " I'm " + age + " years old."

​内嵌表达式:​

val second = "hello, $name. nice to meet you!"
  • 函数的参数默认值

序号

Tips

1

很大程度上能够代替构造函数

​Example:设定参数默认值的方式:​

fun printParams(num: Int, str: String = "hello"){
println("num is $num , str is $str")
}

​用法,注意对于第二个参数,可以传与不传,不传为默认值:​

printParams(123)

特殊情况
​​​默认赋值第一个参数:​

fun printParams(num: Int = 100, str: String) {
print("num is $num , str is $str.")
}
  • Kotlin参数键值对机制

序号

Tips

1

不必按照传统参数顺序赋值

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

​Example:​

fun printParams(num: Int = 100, str: String) {
print("num is $num , str is $str.")
}

fun main() {
printParams(str = "world")
}

次构造函数

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) {}