<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # 基本語法 [TOC] ## 包的定義與導入 包的聲明應處于源文件頂部: ```kotlin package my.demo import kotlin.text.* // …… ``` 目錄與包的結構無需匹配:源代碼可以在文件系統的任意位置。參見[包](http://www.kotlincn.net/docs/reference/packages.html)。 ## 程序入口點 Kotlin 應用程序的入口點是 `main` 函數。 ```kotlin fun main() { println("Hello world!") } ``` ## 函數 帶有兩個 `Int` 參數、返回 `Int` 的函數: ```kotlin //sampleStart fun sum(a: Int, b: Int): Int { return a + b } //sampleEnd fun main() { print("sum of 3 and 5 is ") println(sum(3, 5)) } ``` 將表達式作為函數體、返回值類型自動推斷的函數: ```kotlin //sampleStart fun sum(a: Int, b: Int) = a + b //sampleEnd fun main() { println("sum of 19 and 23 is ${sum(19, 23)}") } ``` 函數返回無意義的值: ```kotlin //sampleStart fun printSum(a: Int, b: Int): Unit { println("sum of $a and $b is ${a + b}") } //sampleEnd fun main() { printSum(-1, 8) } ``` `Unit` 返回類型可以省略: ```kotlin //sampleStart fun printSum(a: Int, b: Int) { println("sum of $a and $b is ${a + b}") } //sampleEnd fun main() { printSum(-1, 8) } ``` 參見[函數](http://www.kotlincn.net/docs/reference/functions.html)。 ## 變量 定義只讀局部變量使用關鍵字 `val` 定義。只能為其賦值一次。 ```kotlin fun main() { //sampleStart val a: Int = 1 // 立即賦值 val b = 2 // 自動推斷出 `Int` 類型 val c: Int // 如果沒有初始值類型不能省略 c = 3 // 明確賦值 //sampleEnd println("a = $a, b = $b, c = $c") } ``` 可重新賦值的變量使用 `var` 關鍵字: ```kotlin fun main() { //sampleStart var x = 5 // 自動推斷出 `Int` 類型 x += 1 //sampleEnd println("x = $x") } ``` 頂層變量: ```kotlin //sampleStart val PI = 3.14 var x = 0 fun incrementX() { x += 1 } //sampleEnd fun main() { println("x = $x; PI = $PI") incrementX() println("incrementX()") println("x = $x; PI = $PI") } ``` 參見[屬性與字段](http://www.kotlincn.net/docs/reference/properties.html)。 ## 注釋 與大多數現代語言一樣,Kotlin 支持單行(或*行末*)與多行(*塊*)注釋。 ```kotlin // 這是一個行注釋 /* 這是一個多行的 塊注釋。 */ ``` Kotlin 中的塊注釋可以嵌套。 ```kotlin /* 注釋從這里開始 /* 包含嵌套的注釋 */ 并且在這里結束。 */ ``` 參見[編寫 Kotlin 代碼文檔](http://www.kotlincn.net/docs/reference/kotlin-doc.html) 查看關于文檔注釋語法的信息。 ## 字符串模板 ```kotlin fun main() { //sampleStart var a = 1 // 模板中的簡單名稱: val s1 = "a is $a" a = 2 // 模板中的任意表達式: val s2 = "${s1.replace("is", "was")}, but now is $a" //sampleEnd println(s2) } ``` 參見[字符串模板](http://www.kotlincn.net/docs/reference/basic-types.html#%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%A8%A1%E6%9D%BF)。 ## 條件表達式 ```kotlin //sampleStart fun maxOf(a: Int, b: Int): Int { if (a > b) { return a } else { return b } } //sampleEnd fun main() { println("max of 0 and 42 is ${maxOf(0, 42)}") } ``` 在 Kotlin 中,*if*也可以用作表達式: ```kotlin //sampleStart fun maxOf(a: Int, b: Int) = if (a > b) a else b //sampleEnd fun main() { println("max of 0 and 42 is ${maxOf(0, 42)}") } ``` 參見[*if*表達式](http://www.kotlincn.net/docs/reference/control-flow.html#if-%E8%A1%A8%E8%BE%BE%E5%BC%8F)。 ## 空值與 *null*檢測 當某個變量的值可以為 *null*的時候,必須在聲明處的類型后添加 `?` 來標識該引用可為空。 如果 `str` 的內容不是數字返回 *null*: ```kotlin fun parseInt(str: String): Int? { // …… } ``` 使用返回可空值的函數: ```kotlin fun parseInt(str: String): Int? { return str.toIntOrNull() } //sampleStart 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' or '$arg2' is not a number") } } //sampleEnd fun main() { printProduct("6", "7") printProduct("a", "7") printProduct("a", "b") } ``` 或者 ```kotlin fun parseInt(str: String): Int? { return str.toIntOrNull() } fun printProduct(arg1: String, arg2: String) { val x = parseInt(arg1) val y = parseInt(arg2) //sampleStart // …… 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) //sampleEnd } fun main() { printProduct("6", "7") printProduct("a", "7") printProduct("99", "b") } ``` 參見[空安全](http://www.kotlincn.net/docs/reference/null-safety.html)。 ## 類型檢測與自動類型轉換 *is*運算符檢測一個表達式是否某類型的一個實例。 如果一個不可變的局部變量或屬性已經判斷出為某類型,那么檢測后的分支中可以直接當作該類型使用,無需顯式轉換: ```kotlin //sampleStart fun getStringLength(obj: Any): Int? { if (obj is String) { // `obj` 在該條件分支內自動轉換成 `String` return obj.length } // 在離開類型檢測分支后,`obj` 仍然是 `Any` 類型 return null } //sampleEnd fun main() { fun printLength(obj: Any) { println("'$obj' string length is ${getStringLength(obj) ?: "... err, not a string"} ") } printLength("Incomprehensibilities") printLength(1000) printLength(listOf(Any())) } ``` 或者 ```kotlin //sampleStart fun getStringLength(obj: Any): Int? { if (obj !is String) return null // `obj` 在這一分支自動轉換為 `String` return obj.length } //sampleEnd fun main() { fun printLength(obj: Any) { println("'$obj' string length is ${getStringLength(obj) ?: "... err, not a string"} ") } printLength("Incomprehensibilities") printLength(1000) printLength(listOf(Any())) } ``` 甚至 ```kotlin //sampleStart fun getStringLength(obj: Any): Int? { // `obj` 在 `&&` 右邊自動轉換成 `String` 類型 if (obj is String && obj.length > 0) { return obj.length } return null } //sampleEnd fun main() { fun printLength(obj: Any) { println("'$obj' string length is ${getStringLength(obj) ?: "... err, is empty or not a string at all"} ") } printLength("Incomprehensibilities") printLength("") printLength(1000) } ``` 參見[類](http://www.kotlincn.net/docs/reference/classes.html)以及[類型轉換](http://www.kotlincn.net/docs/reference/typecasts.html)。 ## `for` 循環 ```kotlin fun main() { //sampleStart val items = listOf("apple", "banana", "kiwifruit") for (item in items) { println(item) } //sampleEnd } ``` 或者 ```kotlin fun main() { //sampleStart val items = listOf("apple", "banana", "kiwifruit") for (index in items.indices) { println("item at $index is ${items[index]}") } //sampleEnd } ``` 參見 [for 循環](http://www.kotlincn.net/docs/reference/control-flow.html#for-%E5%BE%AA%E7%8E%AF)。 ## `while` 循環 ```kotlin fun main() { //sampleStart val items = listOf("apple", "banana", "kiwifruit") var index = 0 while (index < items.size) { println("item at $index is ${items[index]}") index++ } //sampleEnd } ``` 參見 [while 循環](http://www.kotlincn.net/docs/reference/control-flow.html#while-%E5%BE%AA%E7%8E%AF)。 ## `when` 表達式 ```kotlin //sampleStart fun describe(obj: Any): String = when (obj) { 1 -> "One" "Hello" -> "Greeting" is Long -> "Long" !is String -> "Not a string" else -> "Unknown" } //sampleEnd fun main() { println(describe(1)) println(describe("Hello")) println(describe(1000L)) println(describe(2)) println(describe("other")) } ``` 參見 [when 表達式](http://www.kotlincn.net/docs/reference/control-flow.html#when-%E8%A1%A8%E8%BE%BE%E5%BC%8F)。 ## 使用區間(range) 使用 *in*運算符來檢測某個數字是否在指定區間內: ```kotlin fun main() { //sampleStart val x = 10 val y = 9 if (x in 1..y+1) { println("fits in range") } //sampleEnd } ``` 檢測某個數字是否在指定區間外: ```kotlin fun main() { //sampleStart 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") } //sampleEnd } ``` 區間迭代: ```kotlin fun main() { //sampleStart for (x in 1..5) { print(x) } //sampleEnd } ``` 或數列迭代: ```kotlin fun main() { //sampleStart for (x in 1..10 step 2) { print(x) } println() for (x in 9 downTo 0 step 3) { print(x) } //sampleEnd } ``` 參見[區間](http://www.kotlincn.net/docs/reference/ranges.html)。 ## Collections 對集合進行迭代: ```kotlin fun main() { val items = listOf("apple", "banana", "kiwifruit") //sampleStart for (item in items) { println(item) } //sampleEnd } ``` 使用 *in*運算符來判斷集合內是否包含某實例: ```kotlin fun main() { val items = setOf("apple", "banana", "kiwifruit") //sampleStart when { "orange" in items -> println("juicy") "apple" in items -> println("apple is fine too") } //sampleEnd } ``` 使用 lambda 表達式來過濾(filter)與映射(map)集合: ```kotlin fun main() { //sampleStart val fruits = listOf("banana", "avocado", "apple", "kiwifruit") fruits .filter { it.startsWith("a") } .sortedBy { it } .map { it.toUpperCase() } .forEach { println(it) } //sampleEnd } ``` 參見[集合概述](http://www.kotlincn.net/docs/reference/collections-overview.html)。 ## 創建基本類及其實例 ```kotlin fun main() { //sampleStart val rectangle = Rectangle(5.0, 2.0) val triangle = Triangle(3.0, 4.0, 5.0) //sampleEnd println("Area of rectangle is ${rectangle.calculateArea()}, its perimeter is ${rectangle.perimeter}") println("Area of triangle is ${triangle.calculateArea()}, its perimeter is ${triangle.perimeter}") } abstract class Shape(val sides: List<Double>) { val perimeter: Double get() = sides.sum() abstract fun calculateArea(): Double } interface RectangleProperties { val isSquare: Boolean } class Rectangle( var height: Double, var length: Double ) : Shape(listOf(height, length, height, length)), RectangleProperties { override val isSquare: Boolean get() = length == height override fun calculateArea(): Double = height * length } class Triangle( var sideA: Double, var sideB: Double, var sideC: Double ) : Shape(listOf(sideA, sideB, sideC)) { override fun calculateArea(): Double { val s = perimeter / 2 return Math.sqrt(s * (s - sideA) * (s - sideB) * (s - sideC)) } } ``` 參見[類](http://www.kotlincn.net/docs/reference/classes.html)以及[對象與實例](http://www.kotlincn.net/docs/reference/object-declarations.html)。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看