(講課篇)讓小白都能明白的Android開發-2. 跨入Android大門的Kotlin語言篇

大家好,我叫趙健,目前是一名Android開發工程師。今天開始我們一起步入Android開發的世界。本系列課程一共分爲6節課,分別講解了從事Android開發從知道到實際應用幾個難點。本系列課程主要有以下幾部分:

  1. 快速創建一個安卓應用以及基本UI的掌握
  2. 跨入Android大門的Kotlin語言篇
  3. 所有的動畫都來源於這些操作
  4. 自定義UI及一些概念
  5. 快速接入第三方應用
  6. 分析一下優秀的開源程序

上節課我們瞭解到了Android開發的基礎知識,那我們就開始第二節課《跨入Android大門的Kotlin語言篇》

本節課成分爲一下幾小結:

  1. 開始
  2. 基礎
  3. 類與對象
  4. 函數與Lambda表達式
  5. 集合

我們先大概的瞭解一下kotlin所用到的語法,然後逐步深入。

開始

基本用法

基礎語法

包的定義與導入

package my.demo
import kotlin.text.*
// ...

程序的入口

Kotlin應用程序的入口點是main函數:

for main(){
	println("Hello World!")
}

函數

帶有兩個Int參數,返回Int的函數:

fun sum(a:Int, b:Int):Int{
	return a+b
}

將表達式作爲函數體、返回值類型自動推斷的函數:

fun sum(a:Int, b:Int) = a+b

函數返回無意義的值:

fun printSum(a:Int, b:Int):Unit{
	printl("sum of $a and $b is ${a+b}")
}

Unit返回類型可以省略:

fun printSum(a:Int, b:Int){
	printl("sum of $a and $b is ${a+b}")
}

變量

定義只讀局部變量使用關鍵字val定義。只能爲其賦值一次。

val a:Int=1 //立即賦值
val b=2 //自動推斷出`Int`類型
val c:Int //如果沒有初始值類型不能省略
c = 3 //明確賦值

可重新賦值的變量使用var關鍵字:

var x = 5 //自動推斷出Int類型
x += 1

頂層變量:

val PI = 3.14
var x = 0
fun incrementX(){
	x += 1
}

註釋

與大多數現代語言一樣,Kotlin支持單行(或行末)與多行(塊)註釋。

// 這是一個行註釋
/* 這是一個多行的
	塊*/

Kotlin中的塊註釋可以嵌套。

/*註釋從這裏開始
/*包含嵌套的註釋*/
並且再這裏結束*/

字符串模板

var a = 1
// 模板中的簡單名稱:
val s1 = "a is $a"

a = 2
//模板中的任意表達式
val s2 = "${s1.replace("is", "was")}, but now is $a"

條件表達式

fun maxOf(a:Int, b:Int):Int{
	if(a>b){
		return a
	} else {
		return b
	}
}

再Kotlin中,if也可以用作表達式:

fun maxOf(a:Int, b:Int) = if (a>b) a else b

空值與null檢測

當某個變量的值可以爲null的時候,必須再聲明處的類型後添加?來標識引用可爲空。
如果str的內容不是數字返回null:

fun parseInt(str:String):Int?{
	//...
}

使用返回可空值的函數:

fun printProduct(arg1:String, arg2:String){
	val x = parseInt(arg1)
	val y = parseInt(arg2)
	//直接使用x*y會導致編譯錯誤,因爲它們可能爲null
	if(x != null && y!= null) {
		//再空檢測後,x與y會自動轉換爲非空值(non-nullable)
		println(x * y)
	} else {
		println("'$arg1")
	}
}

或者

// ...
// ……
if (x == null) {
    println("Wrong number format in arg1: '$arg1'")
    return
}
if (y == null) {
    println("Wrong number format in arg2: '$arg2'")
    return
}

// 在空檢測後,x 與 y 會自動轉換爲非空值
println(x * y)

類型檢測與自動類型轉換

is運算符檢測一個表達式是否某類型的一個實例。如果一個不可變的局部變量或屬性已經判斷出爲某類型,那麼檢測後的分支中可以當作該類型使用,無需顯示轉換:

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // `obj` 在該條件分支內自動轉換成 `String`
        return obj.length
    }

    // 在離開類型檢測分支後,`obj` 仍然是 `Any` 類型
    return null
}

或者
fun getStringLength(obj: Any): Int? {
    if (obj !is String) return null

    // `obj` 在這一分支自動轉換爲 `String`
    return obj.length
}
甚至
fun getStringLength(obj: Any): Int? {
    // `obj` 在 `&&` 右邊自動轉換成 `String` 類型
    if (obj is String && obj.length > 0) {
      return obj.length
    }

    return null
}

for循環

val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
    println(item)
}

或者
val items = listOf("apple", "banana", "kiwifruit")
for (index in items.indices) {
    println("item at $index is ${items[index]}")
}

while循環

val items = listOf("apple", "banana", "kiwifruit")
var index = 0
while (index < items.size) {
    println("item at $index is ${items[index]}")
    index++
}

when表達式

fun describe(obj: Any): String =
    when (obj) {
        1          -> "One"
        "Hello"    -> "Greeting"
        is Long    -> "Long"
        !is String -> "Not a string"
        else       -> "Unknown"
    }

使用區間(range)

使用in運算符來檢測某個數字是否再指定區間內

val x = 10
val y = 9
if (x in 1..y+1) {
    println("fits in range")
}

檢測某個數字是否再指定區間外:

val list = listOf("a", "b", "c")

if (-1 !in 0..list.lastIndex) {
    println("-1 is out of range")
}
if (list.size !in list.indices) {
    println("list size is out of valid list indices range, too")
}

區間迭代:

for (x in 1..5){
	print(x)
}

或數列迭代:

for (x in 1..10 step 2){
	print(x)
}
println()
for (x in 9 downTo 0 step 3){
	print(x)
}

集合

對集合進行迭代:

for (item in items){
	println(item)
}

使用in運算符來判斷集合內是否包含某實例:

when {
	"orange" in items -> println("juicy")
	"apple" in items -> println("apple is fine too")
}

使用lambda表達式(filter)與映射(map)集合:

val fruits = listof("banana", "avocado", "apple", "kiwifruit")
fruits
	.filter{ it.startsWith("a") }
	.sortedBy { it }
	.map { it.toUpperCase() }
	.forEach { println(it) }

習慣用法

創建數據類

data class Customer(val name:String, val email:String)

會爲Customer類提供以下功能:

  • 所有屬性的getters(對var定義的還有setters)
  • equals()
  • hashCode()
  • toString()
  • copyt()
  • 所有屬性的component1()、component()…等等

函數的默認參數

fun foo(a:Int = 0, b:String = “”) { … }

過濾list

val positives = list.filter {x -> x > 0}

或者可以更短
val positives = list.filter { it > 0 }

檢測元素是否攢在於集合中

if("[email protected]" in emailsList) { ... }
if("[email protected]" !in emailsList) { ... }

字符串內插

println(“Name $name”)

類型判斷

when(x){
	is FOO //->...
	is Bar //->...
	else //-> ...
}

遍歷map/pair型list

for((k,v) in map) {
	println("$k -> $v")
}

k、v可以改成任意名字

使用區間

for (i in 1..100) { …… }  // 閉區間:包含 100
for (i in 1 until 100) { …… } // 半開區間:不包含 100
for (x in 2..10 step 2) { …… }
for (x in 10 downTo 1) { …… }
if (x in 1..10) { …… }

只讀list

val list = listOf(“a”, “b”, “c”)

只讀map

val map = mapOf(“a” to 1, “b" to 2, “c” to 3)

訪問map

println(map[“key”])
map[“key”]=value

延遲屬性

val p:String by lazy{
//計算該字符串
}

擴展函數

fun String.spaceToCamelCase() {......}
"Convert this to camelcase".spaceToCamelCase()

創建單例

object Resource {
    val name = "Name"
}

if not null 縮寫

val files = File("Text").listFiles()
println(files?.size)

if not null and else 縮寫

val files = File("Test").listFiles()

println(files?.size ?: "empty")

if null 執行一個語句

val values = ……
val email = values["email"] ?: throw IllegalStateException("Email is missing!")

在可能會空的集合中取第一元

val emails = …… // 可能會是空集合
val mainEmail = emails.firstOrNull() ?: ""

if not null 執行代碼

val value = ……

value?.let {
    …… // 代碼會執行到此處, 假如data不爲null
}

映射可空值(如果非空的話)

val value = ……

val mapped = value?.let { transformValue(it) } ?: defaultValue 
// 如果該值或其轉換結果爲空,那麼返回 defaultValue。

返回when表達式

fun transform(color: String): Int {
    return when (color) {
        "Red" -> 0
        "Green" -> 1
        "Blue" -> 2
        else -> throw IllegalArgumentException("Invalid color param value")
    }
}

“try/catch”表達式

fun test() {
    val result = try {
        count()
    } catch (e: ArithmeticException) {
        throw IllegalStateException(e)
    }

    // 使用 result
}

“if”表達式

fun foo(param: Int) {
    val result = if (param == 1) {
        "one"
    } else if (param == 2) {
        "two"
    } else {
        "three"
    }
}

返回類型爲 Unit 的方法的 Builder 風格用法

fun arrayOfMinusOnes(size: Int): IntArray {
    return IntArray(size).apply { fill(-1) }
}

單表達式函數

fun theAnswer() = 42

等價於

fun theAnswer(): Int {
    return 42
}

單表達式函數與其它慣用法一起使用能簡化代碼,例如和 when 表達式一起使用:

fun transform(color: String): Int = when (color) {
    "Red" -> 0
    "Green" -> 1
    "Blue" -> 2
    else -> throw IllegalArgumentException("Invalid color param value")
}

對一個對象實例調用多個方法 (with)

class Turtle {
    fun penDown()
    fun penUp()
    fun turn(degrees: Double)
    fun forward(pixels: Double)
}

val myTurtle = Turtle()
with(myTurtle) { // 畫一個 100 像素的正方形
    penDown()
    for (i in 1..4) {
        forward(100.0)
        turn(90.0)
    }
    penUp()
}

配置對象的屬性(apply)

val myRectangle = Rectangle().apply {
    length = 4
    breadth = 5
    color = 0xFAFAFA
}

這對於配置未出現在對象構造函數中的屬性非常有用。

Java 7 的 try with resources

val stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader ->
    println(reader.readText())
}

對於需要泛型信息的泛型函數的適宜形式

//  public final class Gson {
//     ……
//     public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {
//     ……

inline fun <reified T: Any> Gson.fromJson(json: JsonElement): T = this.fromJson(json, T::class.java)

使用可空布爾

val b: Boolean? = ……
if (b == true) {
    ……
} else {
    // `b` 是 false 或者 null
}

交換兩個變量

var a = 1
var b = 2
a = b.also { b = a }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章