main() 函数
main() 函数是每个 Kotlin 程序的起点,在执行之前必须包含在代码中
打印声明
| println("Greetings, earthling!") |
| print("Take me to ") |
| print("your leader.") |
| |
| |
| |
| |
| |
| |
注释
执行顺序
| fun main() { |
| println("I will be printed first.") |
| println("I will be printed second.") |
| println("I will be printed third.") |
| } |
数据类型和变量
可变变量
不可变变量
val goldenRatio =.618
类型推断
字符串 连接
| var streetAddress = " Main St." |
| var cityState = "Brooklyn, NY" |
| |
| println(streetAddress + " " + cityState) |
| |
字符串模板
| var address = " Main St." |
| println("The address is $address") |
| |
内置属性和函数
| var monument = "the Statue of Liberty" |
| |
| println(monument.capitalize()) |
| |
| println(monument.length) |
| |
字符转义序列
| print("\"Excellent!\" I cried. \"Elementary,\" said he.") |
| |
| |
- \n 插入新行
- \t 插入标签
- \r 插入回车
- \’ 插入 单引号
- \” 插入双引号
- \\ 插入反斜杠
- \$ 插入美元符号
算术运算符
+ 加法、- 减法、* 乘法、/ 除法和 % 模数
操作顺序
| + 8 * 2 / 4 - 3 |
| + (4 + 4) / 2 |
| * 2 + 1 * 7 |
| + 18 / 2 * 1 |
| - 3 % 2 + 2 |
增强赋值运算符
| var batteryPercentage = |
| |
| |
| batteryPercentage = batteryPercantage + |
| |
| |
| batteryPercentage += |
递增和递减运算符
| var year = |
| year++ // |
| year |
数学库
| Math.pow(.0, 3.0) |
| Math.min(, 9) |
| Math.max(, 12) |
| Math.round(.7) |
条件表达式
if 表达式
| var morning = true |
| |
| if (morning) { |
| println("Rise and shine!") |
| } |
| |
else 表达式
| var rained = false |
| |
| if (rained) { |
| println("今天不需要给植物浇水。") |
| } else { |
| println("植物需要浇水!") |
| } |
| |
Else-If 表达式
| var age = |
| |
| if (age < ) { |
| println("您被视为未成年人") |
| } else if (age <) { |
| println("您被视为成年人") |
| } else { |
| println("你被认为是高级") |
| } |
| |
| |
比较 运算符
| var myAge = |
| var sisterAge = |
| var cousinAge = |
| |
| myAge > sisterAge |
| myAge < cousinAge |
| myAge >= cousinAge |
| myAge <= sisterAge |
逻辑运算符
| var humid = true |
| var raining = true |
| var jacket = false |
| |
| println(!humid) |
| |
| println(jacket && raining) |
| |
| println(humid || raining) |
| |
AND 运算符: &&
| var humid = true |
| var raining = true |
| var shorts = false |
| var sunny = false |
| |
| |
| println(humid && raining) |
| |
| println(humid && shorts) |
| |
| println(sunny && raining) |
| |
| println(shorts && sunny) |
或运算符:||
| var late = true |
| var skipBreakfast = true |
| var underslept = false |
| var checkEmails = false |
| |
| |
| println(skipBreakfast || late) |
| |
| println(late || checkEmails) |
| |
| println(underslept || late) |
| |
| println(checkEmails || underslept) |
NOT 运算符
| var hungry = true |
| var full = false |
| |
| println(!hungry) |
| println(!full) |
评估顺序
| !true && (false || true) // false |
| /* |
| (false || true) 被评估首先返回 true。 |
| 然后,评估 !true && true 并返回最终结果 false |
| */ |
| !false && true || false // true |
| /* |
| !false 被评估首先返回 true。 |
| 然后评估 true && true,返回 true。 |
| 那么,真|| 评估 false 最终返回 true |
| */ |
嵌套条件
| var studied = true |
| var wellRested = true |
| |
| if (wellRested) { |
| println("祝你今天好运!") |
| if (studied) { |
| println("你应该为考试做好准备!") |
| } else { |
| println("考试前花几个小时学习!") |
| } |
| } |
| |
| |
| |
当表达式
| var grade = "A" |
| |
| when(grade) { |
| "A" -> println("很棒的工作!") |
| "B" -> println("做得太好了!") |
| "C" -> println("你通过了!") |
| else -> println("关!下次一定要多准备!") |
| } |
| |
范围运算符
| var height = |
| |
| if (height in..53) { |
| println("抱歉,您必须至少 英寸才能乘坐过山车") |
| } |
| |
等式运算符
| var myAge = |
| var sisterAge = |
| |
| myAge == sisterAge |
| myAge !== sisterAge |
Collections
不可变列表
var programmingLanguages = listOf("C#", " Java ", "Kotlin", " Ruby ")
可变列表
var fruits = mutableListOf("Orange", " Apple ", "Banana", "Mango")
访问列表元素
| var cars = listOf(" BMW ", " Ferrari ", " Volvo ", " Tesla ") |
| |
| println(cars[]) |
大小属性
| var worldContinents = listOf("Asia", " Africa ", "North America", " South America ", "Antarctica", " Europe ", " Australia ") |
| |
| println(worldContinents.size) |
列表操作
| var seas = listOf("Black Sea", " Caribbean Sea ", "North Sea") |
| println(seas.contains("North Sea")) |
| |
| |
| seas.add("Baltic Sea") |
| |
不可变集
var primaryColors = setOf("Red", "Blue", "Yellow")
可变集
var womenInTech = mutableSetOf("Ada Lovelace", "Grace Hopper", "Radia Perlman", "Sister Mary Kenneth Keller")
访问集合元素
| var companies = setOf(" Facebook ", "Apple", " Netflix ", " Google ") |
| |
| println(companies.elementAt()) |
| |
| println(companies.elementAt()) |
| |
| println(companies.elementAtOrNull()) |
| |
不可变映射
var averageTemp = mapOf("winter" to, "spring" to 60, "summer" to 85, "fall" to 55)
可变映射
var europeanDomains = mutableMapOf("Germany" to "de", " Slovakia " to "sk", "Hungary" to "hu", "Norway" to "no")
检索映射键和值
| var oscarWinners = mutableMapOf("Parasite" to "Bong Joon-ho", "Green Book" to "Jim Burke", "The Shape Of Water" to "Guillermo del Toro") |
| |
| println(oscarWinners.keys) |
| |
| |
| println(oscarWinners.values) |
| |
| |
| println(oscarWinners["Parasite"]) |
| |
添加和删除地图条目
| var worldCapitals = mutableMapOf("United States" to "Washington D.C.", "Germany" to "Berlin", "Mexico" to "Mexico City", "France" to "Paris") |
| |
| worldCapitals.put("Brazil", "Brasilia") |
| println(worldCapitals) |
| |
| |
| worldCapitals.remove("Germany") |
| println(worldCapitals) |
| |
函数
函数
| fun greet() { |
| println("Hey there!") |
| } |
| |
| fun main() { |
| |
| greet() |
| } |
函数参数
| fun birthday(name: String, age: Int) { |
| println("Happy birthday $name! You turn $age today!") |
| } |
| |
| fun main() { |
| birthday("Oscar",) |
| |
| birthday("Amarah",) |
| |
| } |
默认参数
| fun favoriteLanguage(name, language = "Kotlin") { |
| println("Hello, $name. Your favorite programming language is $language") |
| } |
| |
| fun main() { |
| favoriteLanguage("Manon") |
| |
| |
| favoriteLanguage("Lee", "Java") |
| |
| } |
命名参数
| fun findMyAge(currentYear: Int, birthYear: Int) { |
| var myAge = currentYear - birthYear |
| println("I am $myAge years old.") |
| } |
| |
| fun main() { |
| findMyAge(currentYear =, birthYear = 1995) |
| |
| findMyAge(birthYear =, currentYear = 2020) |
| |
| } |
返回声明
| |
| fun getArea(length: Int, width: Int): Int { |
| var area = length * width |
| |
| |
| return area |
| } |
| |
| fun main() { |
| var myArea = getArea(, 8) |
| println("The area is $myArea.") |
| |
| } |
单表达式函数
| fun fullName(firstName: String, lastName: String) = "$firstName $lastName" |
| |
| fun main() { |
| println(fullName("Ariana", "Ortega")) |
| |
| println(fullName("Kai", "Gittens")) |
| |
| } |
函数字面量
| fun main() { |
| |
| var getProduct = fun(num: Int, num2: Int): Int { |
| return num * num2 |
| } |
| println(getProduct(, 3)) |
| |
| |
| |
| var getDifference = { num: Int, num2: Int -> num1 - num2 } |
| println(getDifference(, 3)) |
| |
| } |
类
类示例
| |
| class Student { |
| var name = "Lucia" |
| var semester = "Fall" |
| var gpa =.95 |
| } |
| |
| |
| class Student |
类实例
| |
| class Student { |
| var name = "Lucia" |
| var semester = "Fall" |
| var gpa =.95 |
| } |
| |
| fun main() { |
| var student = Student() |
| |
| println(student.name) |
| |
| println(student.semester) |
| |
| println(student.gpa) |
| |
| } |
主构造函数
| class Student(val name: String, val gpa: Double, val semester: String, val estimatedGraduationYear: Int) |
| |
| fun main() { |
| var student = Student("Lucia",.95, "Fall", 2022) |
| println(student.name) |
| |
| println(student.gpa) |
| |
| println(student.semester) |
| |
| println(student.estimatedGraduationYear) |
| |
| } |
初始化块
| class Student(val name: String, val gpa: Double, val semester: String, val estimatedGraduationYear: Int) { |
| init { |
| println("$name has ${estimatedGraduationYear -} years left in college.") |
| } |
| } |
| |
| fun main() { |
| var student = Student("Lucia",.95, "Fall", 2022) |
| |
| } |
成员函数
| class Student(val name: String, val gpa: Double, val semester: String, val estimatedGraduationYear: Int) { |
| |
| init { |
| println("$name has ${estimatedGraduationYear -} years left in college.") |
| } |
| |
| |
| fun calculateLetterGrade(): String { |
| return when { |
| gpa >=.0 -> "A" |
| gpa >=.7 -> "B" |
| gpa >=.7 -> "C" |
| gpa >=.0 -> "D" |
| else -> "E" |
| } |
| } |
| } |
| |
| |
| fun main() { |
| var student = Student("Lucia",.95, "Fall", 2022) |
| |
| println("${student.name}'s letter grade is ${student.calculateLetterGrade()}.") |
| |
| } |