在2019年Google I/O大会上,Google 发表今后将优先采纳 Kotlin 进行 Android 开发。
一,简介
Kotlin 是一种富裕表现力且简洁的编程语言,不仅能够缩小常见代码谬误,还能够轻松集成到现有利用中。
Google 列举的 Kotlin 的劣势:
- 富裕表现力且简洁:能够应用更少的代码实现更多的性能。表白本人的想法,少编写样板代码。
- 更平安的代码:Kotlin 有许多语言性能,可帮忙你防止null指针异样等常见编程谬误。
- 可互操作:能够在 Kotlin 代码中调用 Java 代码,或者在 Java 代码中调用 Kotlin 代码。Kotlin 可齐全与 Java 编程语言互操作。
- 结构化并发:Kotlin 协程让异步代码像阻塞代码一样易于应用。协程可大幅简化后台任务治理。
更重要的是,Jetpack Compose 仅反对 Kotlin,而不再反对 Java。 Google 提到多平台我的项目可应用 Kotlin 来开发。
二,概念介绍
1. 包的定义和应用
包的定义应该写在文件的顶部。
<code class="kotlin">package com.rustfisher.ktpractice.intro import kotlin.text.* // ...
Kotlin并不要求包名和文件寄存地位严格对应。
2. 程序入口
Kotlin利用的程序入口是main
办法。
<code class="kotlin">fun main() { // .. }
另一个main办法带有参数
<code class="kotlin">fun main(args: Array<String>) { // ... }
3. 规范输入
print
办法将传入的变量打印到规范输出流。
<code class="k">print("Rust ") print("Fisher")
println
打印传入变量并且在最初增加一个换行。
<code class="kotlin">println("an.rustfisher.com") println(42)
4. 办法
上面是一个承受2个Int参数,返回Int的办法。
<code class="kotlin">fun sum(a: Int, b: Int): Int { return a + b }
办法主体能够是一个表达式。它的返回值能够被推断进去。
<code class="kotlin">fun sum(a: Int, b: Int) = a + b
办法能够没有返回值,或者说是返回一个无意义的值(Unit)。
<code class="kotlin">fun printSum(a: Int, b: Int): Unit { println("sum of $a and $b is ${a + b}") }
Unit
能够疏忽不写。
<code class="kotlin">fun printSum(a: Int, b: Int) { println("sum of $a and $b is ${a + b}") }
5. 变量
只能读的变量须要用关键字val
。它们只能被赋值1次。
<code class="kotlin">val a: Int = 1 // 间接赋值 val b = 2 // 主动揣测出是Int类型 val c: Int // 当没有赋初始值时,须要申明类型Type required when no initializer is provided c = 3 // 这里是推延赋值
能够屡次赋值的变量用关键字var
var x = 5 // 主动揣测出是Int型 x += 1
能够在顶部申明变量
val PI = 3.14 var x = 0 fun incrementX() { x += 1 }
6. 创立类与实例
定义一个类,应用class
关键字
class Fisher
类的属性能够放在定义中或者类里。比方上面这个类Rectangle
,形容长方形。
<code class="kotlin">class Rectangle(var height: Double, var length: Double) { var perimeter = (height + length) * 2 }
默认结构器中的变量能够间接应用。这里能够间接应用面积变量perimeter
<code class="kotlin">val rectangle = Rectangle(5.0, 2.0) println("The perimeter is ${rectangle.perimeter}")
对于kotlin v.1.4.30,类的继承用冒号:
来示意。类默认都是final的,不可继承。为了继承,用open
让这个类能被继承。
<code class="kotlin">open class Shape class Rectangle(var height: Double, var length: Double): Shape { var perimeter = (height + length) * 2 }
7. 正文
和其余古代编程语言相似,用//
或者/**/
来正文
<code class="kotlin">// 这里是正文 RustFisher /** * 这是正文 */ /* 这也是正文 */
8. 字符串模版(String tempplates)
间接应用变量,用$
要应用表达式,须要用大括号${}
<code class="kotlin">var a = 1 // 简略应用$ val s1 = "a is $a" a = 2 // 应用办法 val s2 = "${s1.replace("is", "was")}, but now is $a"
9. 条件表达式
<code class="kotlin">fun getMax(a: Int, b: Int): Int { if (a > b) { return a } else { return b } }
Kotlin中,if
也能够写成一个表达式
<code class="kotlin">fun getMax(a: Int, b: Int) = if (a > b) a else b
10. for循环
应用in
<code class="kotlin">val items = listOf("apple", "banana", "kiwifruit") for (item in items) { println(item) }
应用下标
<code class="kotlin">val items = listOf("apple", "banana", "kiwifruit") for (index in items.indices) { println("item at $index is ${items[index]}") }
<code class="kotlin">for (i in 1..3) { println(i) } for (i in 6 downTo 0 step 2) { println(i) }
11. while循环
<code class="kotlin">val items = listOf("apple", "banana", "kiwifruit") var index = 0 while (index < items.size) { println("item at $index is ${items[index]}") index++ }
12. when表达式
when
看起来有点像Java里的witch
,但这两个是不同的货色。
<code class="kotlin">fun describe(obj: Any): String = when (obj) { 1 -> "One" "Hello" -> "Greeting" is Long -> "Long" !is String -> "Not a string" else -> "Unknown" }
13. 范畴
查看一个数字是否在范畴中,应用in
操作
<code class="kotlin">val x = 10 val y = 9 if (x in 1..y+1) { println("在范畴内") }
查看一个数是否超出了范畴
<code class="kotlin">val list = listOf("a", "b", "c") if (-1 !in 0..list.lastIndex) { println("-1 超出了范畴") } if (list.size !in list.indices) { println("list的size也超出了下标范畴") }
遍历一个范畴
<code class="kotlin">for (x in 1..5) { print(x) }
指定步进值
<code class="kotlin">for (x in 1..10 step 2) { print(x) } println() for (x in 9 downTo 0 step 3) { print(x) }
14. 汇合
遍历一个汇合
<code class="kotlin">for (item in items) { println(item) }
查看汇合中是否蕴含某个对象,用in
操作
<code class="kotlin">when { "orange" in items -> println("juicy") "apple" in items -> println("apple is fine too") }
用lambda表达式对汇合进行filter和map操作
<code class="kotlin">val fruits = listOf("banana", "avocado", "apple", "kiwifruit") fruits .filter { it.startsWith("a") } .sortedBy { it } .map { it.toUpperCase() } .forEach { println(it) }
15. 可为null的值和null查看
能够为null的变量,前面须要一个问号?
上面这个办法返回Int或者null
<code class="kotlin">fun parseInt(str: String): Int? { // ... }
应用可能返回null的办法(下面那个办法)
<code class="kotlin">fun printProduct(arg1: String, arg2: String) { val x = parseInt(arg1) val y = parseInt(arg2) // Using `x * y` yields error because they may hold nulls. if (x != null && y != null) { // x 和 y 通过null检测后主动变成了非null值 println(x * y) } else { println("'$arg1' or '$arg2' 不是数字") } }
或者写做
<code class="kotlin">// ... if (x == null) { println("参数谬误 arg1: '$arg1'") return } if (y == null) { println("参数谬误 arg2: '$arg2'") return } // x 和 y 通过null检测后主动变成了非null值 println(x * y)
16. 类型检查和主动转换
用is
来查看某个对象是不是某个类型。 如果确定某个不可变的变量的类型,那前面应用它的时候不必再显式转换
<code class="kotlin">fun getStringLength(obj: Any): Int? { if (obj is String) { // obj曾经主动转换为String类型 return obj.length } // 这里的obj依然是Any类型 return null }
或者用!is
<code class="kotlin">fun getStringLength(obj: Any): Int? { if (obj !is String) return null // 这里的obj曾经主动转换为String类型 return obj.length }
再换个写法
<code class="kotlin">fun getStringLength(obj: Any): Int? { // 这外面的obj曾经主动转换为String类型 if (obj is String && obj.length > 0) { return obj.length } return null }
文末分享:140集 Kotlin 入门到精通全系列(我的项目开发实战)视频教程