funfavoriteLanguage(name: String, language: String = "Kotlin") { println("Hello, $name. Your favorite programming language is $language") }
funmain() { favoriteLanguage("Manon") // Prints: Hello, Manon. Your favorite programming language is Kotlin favoriteLanguage("Lee", "Java") // Prints: Hello, Lee. Your favorite programming language is Java }
命名参数
1 2 3 4 5 6 7 8 9 10 11
funfindMyAge(currentYear: Int, birthYear: Int) { var myAge = currentYear - birthYear println("I am $myAge years old.") }
funmain() { findMyAge(currentYear = 2020, birthYear = 1995) // Prints: I am 25 years old. findMyAge(birthYear = 1920, currentYear = 2020) // Prints: I am 100 years old. }
返回声明
1 2 3 4 5 6 7 8 9 10 11 12 13
// Return type is declared outside the parentheses fungetArea(length: Int, width: Int): Int { var area = length * width
// return statement return area }
funmain() { var myArea = getArea(10, 8) println("The area is $myArea.") // Prints: The area is 80. }
funmain(args: Array<String>) { //这里我们定义一个匿名函数 val operation: (Int, Int) -> Int = { i: Int, i2: Int -> i + i2 } val total = num1AndNum2(100, 200, operation) println(total) //300 }
funmain(args: Array<String>) { //wow哦天哪,Lambda可以做到这样简洁 val total = num1AndNum2(100, 200) { n1, n2 -> n1 + n2 } println(total) }
这里之所以可以把lambda写在外部,是因为operation是最后一个参数。
扩展函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Kotlin File fun String.lettersCount(): Int { var count = 0 // this 相当于我们下面写的字符串具体的内容 // for 可以用 forEach 代替 for (char inthis) { // 判断是不是字母(包括中文) if (char.isLetter()) { count++ } } return count }
classStudent( val name: String, val gpa: Double, val semester: String, val estimatedGraduationYear: Int ) { constructor(name: String, gpa: Double) : this(name, gpa, "Fall", 2024) }
funmain() { val student = Student("Lucia", 3.95) println(student.name) // Prints: Lucia println(student.semester) // Prints: Fall println(student.estimatedGraduationYear) // Prints: 2024 }
类示例
1 2 3 4 5 6 7 8 9
// 具有包含默认值的属性的类 classStudent { var name = "Lucia" var semester = "Fall" var gpa = 3.95 }
// 创建实例并调用函数时,将执行 when 表达式并返回字母等级 funmain() { var student = Student("Lucia", 3.95, "Fall", 2022) // Prints: Lucia has 2 years left in college. println("${student.name}'s letter grade is ${student.calculateLetterGrade()}.") // Prints: Lucia's letter grade is A. }
初始化块
1 2 3 4 5 6 7 8 9 10
classStudent(val name: String, val gpa: Double, val semester: String, val estimatedGraduationYear: Int) { init { println("$name has ${estimatedGraduationYear - 2020} years left in college.") } }
funmain() { var student = Student("Lucia", 3.95, "Fall", 2022) // Prints: Lucia has 2 years left in college. }
Data数据类
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// 默认实现 getter/setter 和 toString 这些方法 dataclassUserInfo( val name: String, val age: Int )