Kotlin-Anko學習(3) Kotlin語法基礎- 關鍵字 package、Import、if、when、for、while、return、break、continue

本系列文章來學習 Kotlin 和 Anko 插件 通過 Kotlin 開發一個 Android 項目。

Kotlin-Anko學習(1) Kotlin、Anko 介紹
Kotlin-Anko學習(2) Kotlin 語法基礎-基本類型
Kotlin-Anko學習(3) Kotlin 語法基礎-關鍵字 package、Import、if、when、for、while、return、break、continue
Kotlin-Anko學習(4) Kotlin語法-類、繼承、抽象類
Kotlin-Anko學習(5) Kotlin語法-屬性、字段、接口

Kotlin語法

Kotlin 語法的學習僅圍繞著 Android 展開,本來不打算寫基礎語法的,自己學習后感覺腦袋還是萌萌噠,所以決定記錄一篇自己學習筆記,方便后續查閱,推薦直接通過官網學習,官方中文網官方英文版結合學習,有些翻譯過來的不好理解,還是直接看英文文檔比較好,并可以提高自己閱讀英語的能力,在語法學習階段我采用Kotlin網頁版編譯工練習。不足之處請多多留言指正,相互學習。

Kotlin package

Kotlin 中,在源文件(.kt)的首行通過 package 聲明包名:如下:

package foo.bar
fun baz() {}
class Goo {}
// ……
  • Kotlin 中包名與文件路徑可以不同(與java區別),用于區分方法與類的唯一性,沒有指明包,該文件的內容屬于無名字的默認包。
  • Kotlin 中 類與函數可以并列在源文件中存在(與java區別)。

Kotlin import

Kotlin 中,包的導入有默認導入和 import 指令導入兩種方式

  • 默認導入的基礎包和 運行在不同的平臺 導入各自的默認包,如下:

    kotlin.*
    kotlin.annotation.*
    kotlin.collections.*
    kotlin.comparisons.* (自 1.1 起)
    kotlin.io.*
    kotlin.ranges.*
    kotlin.sequences.*
    kotlin.text.*
    jvm平臺額外基礎包
    java.lang.*
    kotlin.jvm.*

  • import 導入有類和其他的聲明 如下:

    導入頂層函數及屬性
    導入在對象聲明中聲明的函數和屬性
    導入枚舉常量

Kotlin if表達式

  • 傳統用法
var max = a 
if (a < b) max = b
// With else 
var max: Int
if (a > b) {
    max = a
} else {
    max = b
}
  • 作為表達式,代替三元運算符(條件 ? 然后 : 否則),作為表達式一定要有else
    val max = if (a > b) a else b
  • if 的分支可以是代碼塊,最后的表達式作為該塊的值
  val a = 2
  val b = 1
  val max = if (a > b) {
    print("Choose a")
    a
} else {
    print("Choose b")
    b
}
    print('\n'+max.toString())
}
image.png

Kotlin when 表達式

when 取代了類 C 語言的 switch 操作符 ,when 既可以被當做表達式使用也可以被當做語句使用 whend的集中用法如下:


image.png
  • when 將它的參數和所有的分支條件順序比較,直到某個分支滿足條件
  • 多分支需要用相同的方式處理,則可以把多個分支條件放在一起
  • 任意表達式(而不只是常量)可作為分支條件
  • 采用(in)或者不在(!in)檢測一個值是否在區間中
  • 采用(is)或者不是(!is)檢測是否是一個特定的值
//when替代if-else if 偽代碼:
when {
    x.isOdd() -> print("x is odd")
    x.isEven() -> print("x is even")
    else -> print("x is funny")
}
  • when 也可以用來取代 if-else if鏈

Kotlin for 循環

for 循環可以對任何提供迭代器(iterator)的對象進行遍歷,這相當于像 C# 這樣的語言中的 foreach 循環。

  • 什么是迭代器對象:有一個成員函數或者擴展函數 iterator() 如下:
 public class Array<T> {
     // ......
    /**
     * Creates an iterator for iterating over the elements of the array.
     */
    public operator fun iterator(): Iterator<T>
}

 public interface Iterator<out T> {
    /**
     * Returns the next element in the iteration.
     */
    public operator fun next(): T

    /**
     * Returns `true` if the iteration has more elements.
     */
    public operator fun hasNext(): Boolean
}
    
  • for循環的幾種寫法 如下:
//最常見的寫法
for (item: Int in ints) {
    // ……
}
//通過索引遍歷一個數組或者一個 list
for (i in array.indices) {
    print(array[i])
}
//庫函數 withIndex 
for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}

While 循環

while 和 do..while 的使用與java一致:

while (x > 0) {
    x--
}
//-----------------------
do {
  val y = retrieveData()
} while (y != null) // y 在此處可見

Return、Break和continue

在循環中的使用與java一致,但新增標簽的功能,可以限制跳轉的位置

  • return:默認從最直接包圍它的函數或者匿名函數返回
  • break:終止最直接包圍它的循環
  • continue:繼續下一次最直接包圍它的循環

標簽(abc@)

  • break 使用標簽 用法如下對比:


    最外層for添加標簽.png

    內層for添加標簽.png

    break標簽限制跳轉到指定標簽的循環點,continue使用標簽跟break用法一樣,指定循環的下一次迭代

  • return 使用標簽
//傳統的使用,從foo()函數中返回
fun foo() {
    ints.forEach {
        if (it == 0) return  // nonlocal return from inside lambda directly to the caller of foo()
        print(it)
    }
}
//使用標簽,從lambda表達式中返回
fun foo() {
    ints.forEach lit@ {
        if (it == 0) return@lit
        print(it)
    }
}
//同上,只不過用隱式調用
fun foo() {
    ints.forEach {
        if (it == 0) return@forEach
        print(it)
    }
}
//同上 lambda表達式用匿名函數代替
fun foo() {
    ints.forEach(fun(value: Int) {
        if (value == 0) return  // local return to the caller of the anonymous fun, i.e. the forEach loop
        print(value)
    })
}
//返回一個值的話,在標簽結束后跟值
return@a 1
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。