- Kotlin 教程
- Kotlin - 首頁
- Kotlin - 概述
- Kotlin - 環境搭建
- Kotlin - 架構
- Kotlin - 基本語法
- Kotlin - 註釋
- Kotlin - 關鍵字
- Kotlin - 變數
- Kotlin - 資料型別
- Kotlin - 運算子
- Kotlin - 布林值
- Kotlin - 字串
- Kotlin - 陣列
- Kotlin - 範圍
- Kotlin - 函式
- Kotlin 控制流
- Kotlin - 控制流
- Kotlin - if...Else 表示式
- Kotlin - When 表示式
- Kotlin - For 迴圈
- Kotlin - While 迴圈
- Kotlin - Break 和 Continue
- Kotlin 集合
- Kotlin - 集合
- Kotlin - 列表
- Kotlin - 集合
- Kotlin - 對映
- Kotlin 物件和類
- Kotlin - 類和物件
- Kotlin - 建構函式
- Kotlin - 繼承
- Kotlin - 抽象類
- Kotlin - 介面
- Kotlin - 可見性控制
- Kotlin - 擴充套件
- Kotlin - 資料類
- Kotlin - 密封類
- Kotlin - 泛型
- Kotlin - 委託
- Kotlin - 解構宣告
- Kotlin - 異常處理
- Kotlin 有用資源
- Kotlin - 快速指南
- Kotlin - 有用資源
- Kotlin - 討論
Kotlin 陣列 - component3() 函式
Kotlin 陣列的 component3() 函式檢索陣列物件的第三個元素(即索引 2)。如果陣列大小小於 3 或為空,則此函式會丟擲 IndexOutOfBoundsException 異常。
語法
以下是 Kotlin 陣列 component3() 函式的語法:
operator fun <T> List<T>.component3(): T
引數
此函式不接受任何引數。
返回值
此函式返回任何資料型別的陣列元素。
示例 1
在下面的示例中,讓我們看看如何使用 component3() 函式確定陣列中索引 2 的值。
fun main(args: Array<String>) {
var array = Array(10) { i -> i }
try {
val value = array.component3()
println("The value of the third element of the array is: $value")
} catch (exception : Exception) {
println("Array length is smaller than three")
println(exception.printStackTrace())
}
}
輸出
以下是輸出:
The value of the third element of the array is: 2
示例 2
現在,讓我們看另一個示例,這裡我們建立一個儲存不同型別資料的陣列。然後我們使用 component3() 函式獲取索引 2(即第 3 個元素)的值:
fun main(args: Array<String>) {
var array = arrayOf(10, 23.4, 'c', "tutorialspoint.com")
try {
// use the component3() function
val value = array.component3()
println("The value of the 2nd index of the array is: $value")
} catch (exception : Exception) {
println("Array length is smaller than three")
println(exception.printStackTrace())
}
}
輸出
以下是輸出:
The value of the 2nd index of the array is: c
示例 3
下面的示例建立了一個大小為 2 的陣列,並使用 component3() 函式顯示陣列的第 3 個元素:
fun main(args: Array<String>) {
var array = Array(2) { i -> i }
try {
val value = array.component3()
println("The 3rd element of an array is: $value")
} catch (exception : Exception) {
println("Array length is smaller than 3")
println(exception.printStackTrace())
}
}
輸出
以上程式碼會生成以下輸出。如果發生異常:
Array length is smaller than 3 java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
kotlin_arrays.htm
廣告